java - Jackson 将 Map 合并到 json 对象中

标签 java spring-boot jackson

假设我有以下对象。

class Foo {

    private String name;
    private int age;
    private Map<String, object> extra;

}

public static void main(String[] args) {
    Foo foo = new Foo();
    foo.name = "adam";
    foo.age = 25;
    foo.extra.put("hobbies", /** list of hobbies **/)
    foo.extra.put("firends", /** list of friends **/)

    // convert to json...
}

我想要以下输出...是否可以通过使用自定义序列化来做到这一点?

{
    "name": "adam",
    "age": 25,
    "hobbies": [
      {
         "name": "footbal",
         "level":  1
      }
      { 
        "name": "coding",
        "level": 2
      }
    ],
    "friends": [
      {
        "id": 1
        "name": "jack"
      },
      {
        "id": 2
        "name": "rose"
      }
    ]
}

最佳答案

我找到了实现的方法。通过对 Map 使用 @JsonIgnore @JsonAnyGetter 的组合,但如果您只有自定义对象,则只能使用 @JsonUnwrapped 来获得相同的结果行为。

class Foo {

    private String name;
    private int age;

    @JsonIgnore
    private Map<String, Object> extra;

    @JsonAnyGetter
    public Map<String, Object> getExtra() {
       return extra;
    }
}

关于java - Jackson 将 Map 合并到 json 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946324/

相关文章:

java - 扫描 env 属性文件时忽略 PropertySource 属性文件

intellij-idea - IntelliJ中未使用的属性

java - jackson 忽略了 parent 的所有字段

java - 在文本字段中自动输入

java - 如何在 Struts 2 中使用整个通配符值作为重定向结果

spring-boot - Spring Data Cassandra - 打开新 channel 时出错

Java,将 JSON 数组存储到类并从其他类调用它

java泛型类和通配符

java - 什么时候单例类比只有静态方法的类更受欢迎?

java - Spring RestTemplate 在尝试反序列化对象的嵌套列表时返回 null 对象