简体   繁体   中英

Gson/ Libgdx Json: Serialize class that extends ArrayList

I'm trying to serialize a class A that inherits from ArrayList.

class A<T> extends ArrayList<T>{
    // some stuff ...
}

This works just fine. Output is a simple array of the list's elements. However, if I add fields to class A, they don't get serialized:

class A<T> extends ArrayList<T>{
    String text = "text";
}

leads to the same json output as the class above - the String doesn't appear. I tried this with gson and the libgdx json serializer and they both work the same way. How can I serialize both the class fields AND the elements of the list??

( As a workaround I stored the list as a field in A:

class A<T>{
    ArrayList<T> list;
    String key;
}

but this is not really an elegant solution because I have to implement all list methods (like .add(), .get(), ...) in A by myself. )

Best thanks for help.

Try doing this while parsing:

Type type = new TypeToken<A<WhateverTypeOfArrayListYouWant>>(){}.getType();
gson.fromJson(string, type);

Edit: also for your serialisation issue:

@Override
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
    super.writeObject(s);
    s.writeInt(yourInt);
    s.writeLong(yourLong);
}

@Override
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    super.readObject(s);
    yourInt= s.readInt();
    yourLong= s.readLong();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM