I have an ArrayList<CustomClass> inside of ParentClass which I have written to a file using Gson.toJson(). However when I try to de-serialize the JSON using Gson.fromJson() I only get 1 element of the ArrayList<CustomClass>.
For example I will do the following
public class ParentClass {
private ArrayList<CustomClass> myList = new ArrayList<CustomClass>();
private GrandParentClass nested;
public ParentClass() {
myList.add(new CustomClass("adsf"));
myList.add(new CustomClass("fdsa"));
nested = new GrandParentClass();
}
public int arraySize() {
return myList.size();
}
}
public class GrandParentClass {
private ArrayList<OtherCustomClass> myList = new ArrayList<OtherCustomClass>();
public GrandParentClass() {
myList.add(new CustomClass("asdfasdf.."));
myList.add(new CustomClass("fdsafdsa..."));
}
public int arraySize() {
return myList.size();
}
}
Then when I instantiate a new instance of ParentClass, I use the following to write it to a file.
ParentClass pc = new ParentClass();
Gson gson = new Gson();
String writeThis = gson.toJson(pc); // Produces a perfect JSON reflection myList
FileOutputStream fos = new FileOutputStream(new File("writeto.json"));
fos.write(writeThis);
fos.close();
The JSON object is written in plain text to the .json file
FileInputStream fis = new FileInputStream(new File("writeto.json"));
char c;
StringBuffer sb = new StringBuffer();
while ((c = fis.read()) != -1)
sb.append((char) c);
//Now this is where I only get 1 element of the ArrayList
Gson gson = new Gson();
ParentClass pc = gson.fromJson(sb.toString(), ParentClass.class);
Log.i("SIZE", "Size is " + pc.arraySize()); // Log output: 'Size is 1'
Now, even though I have verified that there are indeed two elements in the ArrayList in the JSON file, only 1 gets loaded into the object using fromJson.
I am serializing these just fine, I would however like to deserialize the ArrayList<OtherCustomClass> inside of the GrandParentClass, which is inside of the ParentClass, in one fell swoop.
Basically I want to serialize ArrayLists nested possibly 3 or 4 layers down in this object heirarchy, and deserialize them into 1 ParentClass that contains these nested ArrayLists<?>. How would this be accomplished?
Thanks
You need to do some additional work when you want to deserialize a collection when generics are involved. This is explained here.
However, I am not sure how this applies to your case, since you have the collection “nested” within a top-level non-generic class.