gpt4 book ai didi

java - jackson 有条件的@JsonUnwrapped

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:38 24 4
gpt4 key购买 nike

我可以有条件地使用@JsonUnwrapped吗?我不想在序列化期间使用它,但想在反序列化对象时使用它。

一种方法是创建两个不同的类或创建一个子类来覆盖在序列化和反序列化时需要表现不同的属性。这听起来不对。还有其他替代方案或 Jackson 解决问题的方法吗?

最佳答案

您可以使用 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'}}

关于java - jackson 有条件的@JsonUnwrapped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com