在Java中使用Jackson的@JsonIdentityInfo批注的重要性?
该 @JsonIdentityInfo当一个对象有一个注释用于父子 在杰克逊库关系。@JsonIdentityInfo 注解 用于指示在序列和反序列化过程的对象的身份。该ObjectIdGenerators.PropertyGenerator是一个抽象的地方-holder类来表示,其中对象标识符来使用来自一个POJO属性的情况下。
语法
@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonIdentityInfo示例
import java.util.*;
import java.io.*;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonIdentityInfoTest {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
User user = new User(115, "Raja", "Ramesh");
Address address = new Address(125, "Madhapur", "Hyderabad", user);
user.addAddress(address);
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(address);
System.out.println(jsonString);
}
}
//用户类别
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")
class User {
private int userId;
private String firstName;
private String lastName;
private List<Address> addresses;
public User(int userId, String firstName, String lastName) {
this.userId = userId;
this.firstName = firstName;
this.lastName = lastName;
this.addresses = new ArrayList<Address>();
}
public int getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void addAddress(Address address) {
addresses.add(address);
}
}
//地址类别
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")class Address {
private int userId;
private String city;
private String street;
private User user;
public Address(int userId, String street, String city, User user) {
this.userId = userId;
this.street = street;
this.city = city;
this.user = user;
}
public int getUserId() {
return userId;
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public User getUser() {
return user;
}
}输出结果
{
"userId" : 125,
"city" : "Hyderabad",
"street" : "Madhapur",
"user" : {
"userId" : 115,
"firstName" : "Raja",
"lastName" : "Ramesh"
}
}