I have a JSON like this
{ "id":1, "name":"Jack", "parent.id":2 }
Note the dot on “parent.id” property
Is it possible to map those JSON to the following classes ?
class Child {
private int id;
private String name;
private Parent parent;
//getter and setter methods
}
class Parent {
private int id;
private String name;
//getter and setter methods
}
So the mapping result would be similar to following statements:
Parent parent = new Parent();
parent.setId(2);
Child child = new Child();
child.setId(1);
child.setName("Jack");
child.setParent(parent); // Here is the result
you can convert this
into this
by using this
and then you can serialize your code by using
JSON.serialize().if you are using Jackson, then you can deserialize the JSON request string by doing any of these:
1. create a custom Jackson deserialize module
2. parse the JSON yourself
the downside of this method is you have to parse for every single JsonRequest with nested objects and it will be messy when there’s a complex nested structure. If this is a problem, I suggest you do the #3
3. create a custom Jackson ObjectMapper class to automate this process
The idea is to build generic process for #2 so that it could handle any nested request.
If you’re using Spring, then the final step is registering this class as Spring bean.
with these set up you can easily use
Hope this helps 🙂