[英]Serializing a pojo as a nested JSON dictionary
鉴于简单的POJO
:
public class SimplePojo {
private String key ;
private String value ;
private int thing1 ;
private boolean thing2;
public String getKey() {
return key;
}
...
}
在序列化成类似的东西(使用Jackson
)时,我没有问题:
{
"key": "theKey",
"value": "theValue",
"thing1": 123,
"thing2": true
}
但是真正让我高兴的是,如果我可以像这样序列化该对象:
{
"theKey" {
"value": "theValue",
"thing1": 123,
"thing2": true
}
}
我在想我需要一个自定义的序列化程序,但是我面临的挑战是插入新字典,例如:
@Override
public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
gen.writeNumberField(value.getKey(), << Here be a new object with the remaining three properties >> );
}
有什么建议么?
您不需要自定义序列化程序。 您可以利用@JsonAnyGetter
注释生成包含所需输出属性的地图。
下面的代码采用上述示例pojo并生成所需的json表示形式。
首先,您已使用@JsonIgnore
注释了所有getter方法,以便让jackson在序列化过程中忽略它们。 唯一会被调用的方法是@JsonAnyGetter
注释的方法。
public class SimplePojo {
private String key ;
private String value ;
private int thing1 ;
private boolean thing2;
// tell jackson to ignore all getter methods (and public attributes as well)
@JsonIgnore
public String getKey() {
return key;
}
// produce a map that contains the desired properties in desired hierarchy
@JsonAnyGetter
public Map<String, ?> getForJson() {
Map<String, Object> map = new HashMap<>();
Map<String, Object> attrMap = new HashMap<>();
attrMap.put("value", value);
attrMap.put("thing1", thing1); // will autobox into Integer
attrMap.put("thing2", thing2); // will autobox into Boolean
map.put(key, attrMap);
return map;
}
}
您需要使用writeObjectFieldStart
方法来写入字段并以相同的类型打开新的JSON Object
:
class SimplePojoJsonSerializer extends JsonSerializer<SimplePojo> {
@Override
public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectFieldStart(value.getKey());
gen.writeStringField("value", value.getValue());
gen.writeNumberField("thing1", value.getThing1());
gen.writeBooleanField("thing2", value.isThing2());
gen.writeEndObject();
gen.writeEndObject();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.