Reputation: 4780
I have a JSON file that is being parsed with Gson. The problem I have is there are nested arrays in the Json e.g.
"assets":[
{
"Address":"Crator1, The Moon",
"Title":"The Moon",
"AudioFile":null,
"Categories":[
{
"CategoryName":"Restaurants",
"Description":"blah blah",
"ExternalLink":"",
"File":"",
"FileName":"0",
"CategoryID":0,
"ParentCategoryID":786,
"Id":334,
"Image":"",
},
I know it's invalid, it's just for an example. So based on previous questions I have asked and research I believe I should have my code as follows in order to parse the JSON correctly:
public class JsonAssets implements Parcelable{
String Address;
String Title;
String AudioFile;
Categories[] categories;
private class Categories{
String CategoryName;
String Description;
String ExternalLink;
String File;
String FileName;
int CategoryID;
int ParentCategoryID;
int Id;
String Image;
}
}
The class is passed as follows:
JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.beginObject();
reader.nextName();
reader.beginArray();
JsonObject obj = null;
while (reader.hasNext()) {
try{
switch(type){
case ASSET_UPDATE:
obj = gson.fromJson(reader, JsonAsset.class);
break;
}
So I read and write the address, audio file as so:
public static final Parcelable.Creator<AssetJson> CREATOR = new Parcelable.Creator<AssetJson>() {
public AssetJson createFromParcel(Parcel in) {
return new AssetJson(in);
}
public AssetJson[] newArray(int size) {
return new AssetJson[size];
}
};
public void writeToParcel(Parcel paramParcel, int paramInt) {
paramParcel.writeString(Address);
paramParcel.writeString(Title);
paramParcel.writeString(AudioFile);
}
private JsonAsset(Parcel in) {
Address = in.readString();
Title = in.readString();
AudioFile = in.readString();
}
The problem I have is I don't know how to read and write Categories[] to the parcel. The fact that it is an object array has me stumped.
This is my first experience with parcelables and I'm trying to take over someone elses code. So if anyone could explain how I would parcel an object array, I'd greatly appreciate it.
Thank you!
Upvotes: 0
Views: 2384
Reputation: 4780
I managed to find the correct solution (for me) so if anyone else is coming up against this, follow this link: http://www.javacreed.com/gson-deserialiser-example/
It shows how to parse nested array and deserialize.
Upvotes: 0
Reputation: 4344
Simple, first make your Category class implement Parcelable, implement all the logic for reading and writing back there, then use Parcel class writeParcelableArray
method to write an array of parcelables.
Hope this help.
Upvotes: 1