给定简单的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;
}
}
关于java - 将 pojo 序列化为嵌套 JSON 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57153946/