给出简单的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 >> );
}
有什么建议吗?
答案 0 :(得分:0)
您需要使用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();
}
}
答案 1 :(得分:0)
您不需要自定义序列化程序。您可以利用@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;
}
}