This might be a bit long so please bear with me..
I’m working on a project in Android. I have a JSON string that i need to deserialize into objects representing the JSON structure, the JSON string is something like below:
{"parents":[
{"parent":{
"id":1,
"name":"Sam",
"childs":[
{
"child":{
"id":1,
"name":"Alice",
"books":[
{
"book":{
"id":1,
"name":"Alice in Wonderland"
}
}
]
}
}
]
}
}
]}
Note that for arrays there are repeating values (i.e. many parent and many child) i just put one line here to make it short.
With this i created classes to accomodate the structure:
public class Containers{
private List<Parent> parents;
//setter and getter..
}
public static class Parent extends CommonItem {
private List<Child> childs;
//setter and getter..
}
public static class Child extends CommonItem {
private List<Book> books;
//setter and getter..
}
public class CommonItem{
private int id;
private String name;
//setter and getter
}
Note that i’d created a common class to accommodate the repeating attributes.
Below is how i parse them using GSON:
Gson gson = new Gson();
Containers parents = gson.fromJson(jsonString, Containers.class);
After parsing (there’re no error) i try to retrieve the objects. The number of object count in the parents list is correct (i.e. there are 5 parents in the JSON string, and there are 5 Parent objects in the parents List). However, all their attributes are not there, and the child tree are missing as well.
I’d tried numerous configuration, including remove the extended class and put all the id and name in the respective classes but the result is still the same.
Anyone can give me any pointer that where did i go wrong?
Thanx a bunch!
Your JSON and Java class mismatch.
Lets read
Your top object has a
Listof class that hasparentsas it’s attribute. Your Java classContainerhasparentsattribute. Good.Now this list
parentsis aListof objects that hasparentattribute. Does yourParentobject hasparentattribute? No.Go further down, each
Parenthasid,name, and aListof objects aschilds(children, should be) attribute that haschildattribute, does yourChildclass has it? No.Similarly, goes for
books.Did you try your classes on JSON like