gallium gallium -4 years ago 80
Java Question

How to serialize/deserialize (JSON) ArrayLIst<A> wich has an ArrayLIst<B> as field in Java

I'm new in Android programming's world and I've some problems using JSON to serialize and deserialize an ArrayList of custom objects. I know how to serialize an object but not if it has an ArrayList as a field.

I found the GSON library but I don't really know how to use it.

I have an ArrayList of a class A which has an ArrayList of a class B. I'm serializing class A using a toJSON() method:

public class A
{
//Some fields like title, id...
private String mTitle;
private ArrayList<B> mArray; //I don't know how to serialize/deserialize this field

public A(){...}
public A(JSONObject json){...}

public JSONObject toJSON() throws JSONException //method I use to convert my object into a JSONObject
{
JSONObject json = new JSONObject();
json.put("TITLE",mTitle);

return json;
}

}

public class B
{
//some fields like a double, String...
public B(){...}

}


If my problem isn't clear, just ask for more details.

Sorry if I made mistakes.
Thanks for your help.

Answer Source

In case of collection, you have to specify the type.

See a Guide User

In your case for example, i think this will resolve:

Type collectionType = new TypeToken<Collection<A>>(){}.getType();
Collection<A> list = gson.fromJson(json, collectionType);   

Where Ais your class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download