序列化以下类的对象yeilds string like
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
的确切相反的行上答案 0 :(得分:3)
您可以使用此类解决方法(但更喜欢使用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的反序列化示例
答案 1 :(得分:-1)
添加另一个名为Address
的课程,如下所示:
public class Address implements Serializable {
private Integer pinCode;
private String city;
// getters /setters
}
然后在Address
类中使用User
类,如下所示:
public class User implements Serializable {
private Integer id;
private String name;
private Address address;
// getters /setters
}
现在Jackson给你json字符串:
{
"id": 1,
"name": "XYZ",
"address": {
"pinCode": 123456,
"city": "ABC"
}
}
@JsonProperty(“address.pinCode”)用于在json中设置字段名称。有关详细信息,请参阅此处的文档JsonProperty