简体   繁体   中英

Jackson merge Map into json object

Let's say I have the following object.

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...
}

and I want the following output... Is it possible to do this by using custom serialize?

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

I have found a way to achieve. by using a combination of @JsonIgnore @JsonAnyGetter for Map, but if you have just custom object you can use only @JsonUnwrapped to get the same behavior.

class Foo {

    private String name;
    private int age;

    @JsonIgnore
    private Map<String, Object> extra;

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

String json = objectMapper.writeValueAsString(foo);
System.out.println(json);

if you want to write the json directly in output strem

ObjectMapper objectMapper = new ObjectMapper();

objectMapper.writeValue(outputStream, foo);

Almost there, hobbies is List of Map and also you need getters and setters

class Foo {

  private String name;
  private int age;
  private List<Map<String, object>> hobbies;

  // Getters and Setters

}

And in main method use ObjectMapper

public static void main(String[] args) {
Foo foo = new Foo();
foo.SetName("adam");
foo.SetAge(25);

Map<String,Object> map1 = Map.of("name","footbal","level",1);  //from jdk-9 you can use Map.of and List.of to create immutable objects
List<Map<String,Object>> hobbies = List.of(map1);      

foo.setHobbies(hobbies);

// Use ObjectMapper to convert object to json

ObjectMapper objectMapper = new ObjectMapper();

String json = objectMapper.writeValueAsString(foo);
System.out.println(json);


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM