序列化以下类的对象会产生类似的字符串
public class User implements Serializable{
private Integer id;
private String name;
private Integer pinCode;
private String city;
// getters /setters
}
{"id":1,"name":"XYZ","pinCode":123456,"city":"ABC"}
但是我们希望属性 pinCode 和 city 应该成为新 Json 节点(例如地址节点)的一部分。
所以我对结果的期望是:
{
"id": 1,
"name": "XYZ",
"address": {
"pinCode": 123456,
"city": "ABC"
}
}
是否可以在不重新组织类结构并使用 Json 注解的情况下完成此任务
与 @JsonUnwrapped 完全相反的行
最佳答案
您可以使用这样的解决方法(但首选使用 JsonSerialize):
public class User implements Serializable{
private Integer id;
private String name;
@JsonIgnore
private Integer pinCode;
@JsonIgnore
private String city;
@JsonProperty("address")
public Map<String, Object> getAddress() {
Map<String, Object> map = new HashMap<>();
map.put("pinCode", pinCode);
map.put("city", city);
return map;
}
//Deserealization
public void setAddress(Map<String, Object> map) {
if(map!=null) {
city = (String) map.get("city");
pinCode = (Integer) map.get("pinCode");
}
}
// getters /setters
}
感谢@hemantvsn提供反序列化示例
关于java - Jackson 将属性序列化并包装到一个新对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724834/