Heim  >  Artikel  >  Java  >  Wie ignoriere ich mehrere Eigenschaften eines JSON-Objekts in Java?

Wie ignoriere ich mehrere Eigenschaften eines JSON-Objekts in Java?

王林
王林nach vorne
2023-09-18 22:29:02660Durchsuche

Die Annotation

Wie ignoriere ich mehrere Eigenschaften eines JSON-Objekts in Java?

@JsonIgnorePropertiesJackson kann verwendet werden, um eine Liste von Eigenschaften oder Feldern einer Klasse anzugeben, die ignoriert werden sollen. @JsonIgnoreProperties Annotation kann vor einer Klassendeklaration statt vor einer einzelnen Eigenschaft oder einem zu ignorierenden Feld platziert werden.

Syntax

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties

Beispiel

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnorePropertiesTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("120", "Ravi", "Hyderabad");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
@JsonIgnoreProperties({"id", "address"}) <strong>
</strong>class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   public Customer(String id, String name, String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   public String getId() {
      return id;
   }
   public String getName() {
      return name;
   }
   public String getAddress() {
      return address;
   }
<strong>   </strong>@Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}

Ausgabe

Customer [id=120, name=Ravi, address=Hyderabad]
JSON: {"name":"Ravi"}
---------
JSON: {"id":"130","name":"Rahul", "address":"Mumbai"}
Customer [id=null, name=Rahul, address=null]

Das obige ist der detaillierte Inhalt vonWie ignoriere ich mehrere Eigenschaften eines JSON-Objekts in Java?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:tutorialspoint.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen