java - 将 pojo 序列化为嵌套 JSON 字典

标签 java json serialization jackson json-serialization

给定简单的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/

相关文章:

java - 使用 python API 进行的训练作为 java API 中 LabelImage 模块的输入?

java - 如何判断 JFrame 窗口是否已经打开?

python - PySpark使用RDD和json.load解析Json

java - 在 Java 中解码包含值类型对象的 CDR 流时如何更改字节顺序

java - 如何将 TreeViewer 单元格的一部分设为粗体?

java - 抛出验证异常 - 带有行号

javascript - 在 Jquery 中选择第一个搜索项而不单击它

javascript - 在 $.post() 中获取返回数据的数量

java - Hibernate 和序列化

c# - 不使用 XmlInclude 进行序列化