Serialize nested object json jackson
You could use a custom serializer for that. However, the easiest way to achieve what you want is using a Map
to wrap the C
instance:
Map<String, Object> map = new HashMap<>();
map.put("rootC", c);
Your classes would be like:
@JsonRootName(value = "rootA")
public class A {
public String name;
public B b;
}
public class B {
@JsonProperty("rep")
public Object representation;
public String bar;
}
public class C {
public BigInteger ste;
public String cr;
}
The code to create the JSON would be:
A a = new A();
a.name = "MyExample";
B b = new B();
b.bar = "something";
C c = new C();
c.cr = "C1";
c.ste = new BigInteger("7");
a.b = b;
Map<String, Object> map = new HashMap<>();
map.put("rootC", c);
b.representation = map;
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(a);
And the generated JSON would be:
{
"rootA" : {
"name" : "MyExample",
"b" : {
"rep" : {
"rootC" : {
"ste" : 7,
"cr" : "C1"
}
},
"bar" : "something"
}
}
}
Siddharth Trikha
Updated on June 04, 2022Comments
-
Siddharth Trikha almost 2 years
I am using Jackson json library to convert my POJOs to json:
public class A { public String name; public B b; } public class B { public Object representation; public String bar; }
I want to serialize an instance of
A
into JSON. I am going to use theObjectMapper
class from Jackson:objectMapperPropertiesBuilder.setSerializationFeature(SerializationFeature.WRAP_ROOT_VALUE); objectMapperPropertiesBuilder.setAnnotationIntrospector(new CustomAnnotionIntrospector());
Here annotation introspector picks root element as all these are JAXB classes with annotations like
@XmlRootElement
and@XmlType
:Ex: If I set in
Object
representation:public class C { public BigInteger ste; public String cr; }
Using this code, my JSON would look like this:
rootA: { "name": "MyExample", "b": { "rep": { "ste": 7, "cr": "C1" }, "bar": "something" } }
But I want the root element appended to my nested
Object
too. Object can be any custom POJO.So in this case, I would want root element of class
C
appended in my JSON conversion. So:rootA: { "name": "MyExample", "b": { "rep": { "rootC": { "ste": 7, "cr": "C1" } }, "bar": "something" } }
How can I add the root element of a nested object in JSON conversion ? All the
objectMapper
properties I specified will be applicable toclass A
. Do I have to write a custom serializer to apply some properties to nested object ?