【发布时间】:2014-10-15 00:47:25
【问题描述】:
我可以有条件地使用@JsonUnwrapped 吗?我不想在序列化期间使用它,但想在反序列化对象时使用它。
一种方法是创建两个不同的类,或者创建一个子类来覆盖在序列化和反序列化时需要表现不同的属性。这听起来不对。任何其他替代方案或杰克逊解决问题的方法?
【问题讨论】:
-
投反对票有什么理由吗?
我可以有条件地使用@JsonUnwrapped 吗?我不想在序列化期间使用它,但想在反序列化对象时使用它。
一种方法是创建两个不同的类,或者创建一个子类来覆盖在序列化和反序列化时需要表现不同的属性。这听起来不对。任何其他替代方案或杰克逊解决问题的方法?
【问题讨论】:
有一种更简单的方法可以实现仅基于注释的相同结果:
@JsonUnwrapped(prefix = "name_")
@JsonProperty(access = READ_ONLY)
private Name nameObject;
// method will deserialize original JSON and set it to unwrapped field
@JsonSetter
public void setName(Name name) {
this.nameObject = name;
}
// simple getter
@JsonIgnore
public Name getName() {
return this.nameObject;
}
【讨论】:
您可以使用MixIn feature。使用此功能 POJO 类与 Jackson 注释分离。您可以使用MixIn 在运行时添加必要的注释。见下例:
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTest {
private static final String UNWRAPPED_JSON = "{\n" +
" \"age\" : 13,\n" +
" \"first\" : \"Huckleberry\",\n" +
" \"last\" : \"Finn\"\n" +
"}";
@Test
public void test() throws IOException {
System.out.println("### Serialize without unwrapped annotation ###");
ObjectMapper serializer = new ObjectMapper();
System.out.println(serializer.writerWithDefaultPrettyPrinter().writeValueAsString(createParent()));
System.out.println("### Deserialize with unwrapped annotation ###");
ObjectMapper deserializer = new ObjectMapper();
deserializer.addMixInAnnotations(Parent.class, ParentMixIn.class);
System.out.println(deserializer.readValue(UNWRAPPED_JSON, Parent.class));
}
private Parent createParent() {
Name name = new Name();
name.first = "Tom";
name.last = "Sawyer";
Parent parent = new Parent();
parent.setAge(12);
parent.setName(name);
return parent;
}
}
class Parent {
private int age;
private Name name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
@Override
public String toString() {
return "Parent{" +
"age=" + age +
", name=" + name +
'}';
}
}
interface ParentMixIn {
@JsonUnwrapped
Name getName();
}
class Name {
public String first, last;
@Override
public String toString() {
return "Name{" +
"first='" + first + '\'' +
", last='" + last + '\'' +
'}';
}
}
上面的程序打印:
### Serialize without unwrapped annotation ###
{
"age" : 12,
"name" : {
"first" : "Tom",
"last" : "Sawyer"
}
}
### Deserialize with unwrapped annotation ###
Parent{age=13, name=Name{first='Huckleberry', last='Finn'}}
【讨论】: