Reputation: 5637
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"
}
]
}
Upvotes: 0
Views: 539
Reputation: 5637
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;
}
}
Upvotes: 1
Reputation: 40068
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);
}
Upvotes: 0
Reputation: 418
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);
Upvotes: 0