gpt4 book ai didi

java - jackson 图书馆 : custom mapping of a Java object in a JSON element

转载 作者:行者123 更新时间:2023-11-29 07:41:59 25 4
gpt4 key购买 nike

我有两个类(class)

public class Person {
private long id;
private String name;
private Gender gender;

// getter and setter omitted
}

public class Gender {
private long id;
private String value;

// getter and setter omitted
}

默认情况下,Person 对象与 Jackson 库的 JSON 映射是:

{
id: 11,
name: "myname",
gender: {
id: 2,
value: "F"
}
}

我想知道如何配置 Jackson 以获得:

{
id: 11,
name: "myname",
gender: "F"
}

我不想映射所有 Gender 对象,而只映射它的 value 属性。

最佳答案

您可以使用自定义序列化程序:

    public class GenderSerializer extends JsonSerializer<Gender> {

public GenderSerializer() {
}

@Override
public void serialize(Gender gender, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(gender.getValue());
}
}

在你的 Person 类中:

public class Person {
private long id;
private String name;
@JsonSerialize(using = GenderSerializer.class)
private Gender gender;

}

关于java - jackson 图书馆 : custom mapping of a Java object in a JSON element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163095/

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