[英]Jackson serialize and wrap attributes into a new Object
Serializing object of the following class 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"}
But we want that attributes pinCode and city should be a part of new Json node say address node. 但是我们希望属性pinCode和city应该成为新的Json节点(例如地址节点)的一部分。
So my expectation of the result is: 所以我对结果的期望是:
{
"id": 1,
"name": "XYZ",
"address": {
"pinCode": 123456,
"city": "ABC"
}
}
Can this be accomplished without re-organizing the class structure and by using Json annotations 无需重新组织类结构并使用Json注释即可完成此操作
on the exact opposite lines of @JsonUnwrapped 在@JsonUnwrapped的完全相反的行上
you can use such workaround(but preferred to use JsonSerialize): 您可以使用以下解决方法(但最好使用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
}
Thanks to @hemantvsn for deserialization example 感谢@hemantvsn提供反序列化示例
Add another class called Address
like below: 添加另一个名为
Address
类,如下所示:
public class Address implements Serializable {
private Integer pinCode;
private String city;
// getters /setters
}
Then use Address
class inside User
class like below: 然后在
User
类中使用Address
类,如下所示:
public class User implements Serializable {
private Integer id;
private String name;
private Address address;
// getters /setters
}
Now Jackson give you json string like : 现在,杰克逊给您提供json字符串,例如:
{
"id": 1,
"name": "XYZ",
"address": {
"pinCode": 123456,
"city": "ABC"
}
}
@JsonProperty("address.pinCode") used to set field name in json. @JsonProperty(“ address.pinCode”)用于在json中设置字段名称。 Please see doc here for more detail JsonProperty
请参阅文档以获取更多详细信息JsonProperty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.