How do I use Google's Gson API to deserialize JSON properly?
Posted
by FK82
on Stack Overflow
See other posts from Stack Overflow
or by FK82
Published on 2010-05-19T09:47:57Z
Indexed on
2010/05/19
9:50 UTC
Read the original article
Hit count: 326
Hi,
In short, this is a sketch of the JSON object I want to parse in JAVA:
{
object1: {
item1: //[String | Array | Object] ,
item2: // ...
//<> more items
object2: { // }
//<> more objects
}
These are the POJO s I created for parsing (I'll leave out the import
statements for brevity's sake):
(1) The representation of the complete JSON object
public class JObjectContainer {
private List<JObject> jObjects ;
public JObjectContainer() { // }
//get & set methods
}
(2) The representation of the nested objects:
public class JObject {
private String id ;
private List<JNode> jObjects ;
public JObject() { // }
//get & set methods
}
(3) The representation of the items:
public class JNode {
private JsonElement item1 ;
private JsonElement item2 ;
//<> more item fields
public JNode() { // }
//get & set methods
}
Now, creating a Gson instance (FileReader
for importing the jsonFile
),
Gson gson = new Gson() ;
JObjectContainer joc = gson(jsonFile,JObjectContainer.class) ;
I get a NullPointerException
whenever I try to access the parseable object (e.g. through a ListIterator
). Gson does however create an object of the class I specified and does not throw any subsequent errors.
I know that this has been done before. So, what am I missing?
TIA
© Stack Overflow or respective owner