我们什么时候可以在Java中调用@JsonAnyGetter和@JsonAnySetter注释?
该@JsonAnyGetter注解 让使用映射 作为容器 的属性,我们要序列化JSON和@JsonAnySetter注释 指示杰克逊调用同样的设置方法为所有无法识别领域的JSON对象,这意味着,是不是所有的领域已经映射到Java对象中的属性或设置方法。
语法
public @interface JsonAnyGetterpublic @interface JsonAnyGetter
示例
import java.io.*;import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
public class JsonAnyGetterAndJsonAnySetterTest {
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
Employee emp1 = new Employee();
emp1.setFirstName("Adithya");
emp1.setLastName("Sai");
emp1.setEmpId(125);
emp1.getAdditionalInformation().put("technology1", "Machine Learning");
emp1.getAdditionalInformation().put("technology2", "Robotics");
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1);
System.out.println(jsonStr);
System.out.println("将JSON反序列化为对象:");
Employee emp2 = mapper.readValue(jsonStr, Employee.class);
System.out.println("id : " + emp2.getEmpId());
System.out.println("firstName : " + emp2.getFirstName());
System.out.println("lastName : " + emp2.getLastName());
System.out.println("Additional information : " + emp2.getAdditionalInformation());
}
}
//员工阶层
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"firstName", "lastName", "technologies", "empId" })
class Employee {
@JsonProperty("EMPLOYEE_ID")
private int empId;
@JsonProperty("EMPLOYEE_FIRST_NAME") private String firstName; @JsonProperty("EMPLOYEE_LAST_NAME") private String lastName;
private Map<String, String> additionalInformation = new HashMap<>();
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
} @JsonAnyGetter public Map<String, String> getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(Map<String, String> additionalInformation) {
this.additionalInformation = additionalInformation;
} @JsonAnySetter
public void setAdditionalProperty(final String name, final String value) {
this.additionalInformation.put(name, value);
}
}
输出结果
{"EMPLOYEE_FIRST_NAME" : "Adithya",
"EMPLOYEE_LAST_NAME" : "Sai",
"EMPLOYEE_ID" : 125,
"technology1" : "Machine Learning",
"technology2" : "Robotics"
}
将JSON反序列化为对象:
id : 125
firstName : Adithya
lastName : Sai
Additional information : {technology1=Machine Learning, technology2=Robotics}
以上是 我们什么时候可以在Java中调用@JsonAnyGetter和@JsonAnySetter注释? 的全部内容, 来源链接: utcz.com/z/322367.html