3
votes

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(){...}   
}
3

3 Answers

2
votes

In case of collection, you must specify the type.

See a Guide User

In your case, I think this will solve:

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

Where A is your class.

0
votes

Are you trying to use Parcelable? Try something like this (pseudo code):

public class ParcelableObject implements Parcelable{

List<ObjectB> _customObjectList = new ArrayList<ObjectB>();

@Override
public void writeToParcel(Parcel outParcel_, int arg1) {
outParcel_.writeTypedList(_customObjectList); //where _customObjectList is your list variable
}


//Then in your constructor which takes in a Parcel:

public ParcelableObject(Parcel parcelIn_) {
parcelIn_.readTypedList(_customObjectList, ObjectB.CREATOR);
}

}

ObjectB

public class ObjectB implements Parcelable{

int _randomInt;

    public static final Parcelable.Creator<ObjectB> CREATOR = new Parcelable.Creator<ObjectB>() {
        @Override
        public ObjectBcreateFromParcel(Parcel in) {
            return new ObjectB(in);
        }

        @Override
        public ObjectB[] newArray(int size) {
            return new ObjectB[size];
        }
    };

    public ObjectB(Parcel parcelIn_) {
          _randomInt = parcelIn_.readInt();

    }



    @Override
    public void writeToParcel(Parcel out_, int flags) {
        out_.writeInt(_randomInt);
    }
}
0
votes

What is better is to do something like that:

List<YourObject> myList = new Genson().deserialize(dta.toString(), List.class);