gpt4 book ai didi

java - POJO 中单个字段上的内部对象值(JSON 对象)的映射

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:44 24 4
gpt4 key购买 nike

我使用 Jackson 在 java POJO 上进行 json 映射。我想要的是将 JSON 的内部字段映射到我的父 java POJO,并且需要询问是否可以通过任何注释来实现?我的JSON如下

{
"email": "xyz@abc.com",
"name": {
"forenames": "John",
"surname": "Doe"
}
}

POJO 是:

 public class CustomerVo {

@JsonProperty("last4")
private String emailAddress;

/*is there any annotation available that I can use to concat
fornames and surname in 'customeName' ?? */
private String customerName;

}

感谢您提前提供的帮助。

最佳答案

首先,您可以编写一个类 CustomerName 来序列化您的属性。如果您不想实现单独的类,则需要自定义 JsonDeserializerJsonSerializer (顺便说一句:比仅仅编写 CustomerName 类多一点代码)。例如,

public class CustomerNameJsonSerializer extends JsonSerializer<String> {

@Override
public void serialize(String customerName, JsonGenerator jg, SerializerProvider sp) throws IOException {
jg.writeStartObject();

jg.writeFieldName("forenames");
jg.writeString(/* extract your forenames from customerName */);

jg.writeFieldName("surname");
jg.writeString(/* extract your surname from customerName */);

jg.writeEndObject();
}

}

public class CustomerNameJsonDeserializer extends JsonDeserializer<String> {

@Override
public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
TreeNode tree = jp.readValueAsTree();
TextNode forenames = (TextNode) tree.path("forenames");
TextNode surname = (TextNode) tree.path("surname");

return forenames.asText() + ":" + surname.asText();
}

}

public class CustomerVo {

@JsonProperty("last4")
private String emailAddress;

@JsonProperty("name")
@JsonSerialize(using = CustomerNameJsonSerializer.class)
@JsonDeserialize(using = CustomerNameJsonDeserializer.class)
private String customerName;

}

关于java - POJO 中单个字段上的内部对象值(JSON 对象)的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507648/

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