我知道杰克逊允许使用@JsonUnwrapped
创建平面json,以便像
public class Person {
public int age;
@JsonUnwrapped public Name name;
public class Name {
public String first, last;
}
}
将被序列化为
{"age" : 99, "first" : "Name", "last" : "Surname"}
然而,我找不到相反的方法 - 有类似
的类public class Person {
public int age;
public String firstName, lastName;
}
并将其对象序列化为
并从中反序列化{"age" : 99, "name" : {"first" : "Name", "last" : "Surname"}}
这可能是使用Jackson 1.9吗?
答案 0 :(得分:6)
我偶然发现了这个相当古老的问题,因为我正在寻找相同的问题。我最终这样做了:
public class Person {
public int age;
@JsonIgnore
public String firstName, lastName;
protected void setName(PersonName name) {
firstName = name.first;
lastName = name.last;
}
protected PersonName getName() {
return new PersonName(firstName, lastName);
}
protected static class PersonName {
private final String first, last;
@JsonCreator
public PersonName(@JsonProperty("first") String first, @JsonProperty("last") String last) {
this.first = first;
this.last = last;
}
}
}