简体   繁体   English

Gson / Libgdx Json:序列化扩展ArrayList的类

[英]Gson/ Libgdx Json: Serialize class that extends ArrayList

I'm trying to serialize a class A that inherits from ArrayList. 我正在尝试序列化从ArrayList继承的类A。

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: 但是,如果我将字段添加到A类,则它们不会被序列化:

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

leads to the same json output as the class above - the String doesn't appear. 导致与上面的类相同的json输出-字符串不出现。 I tried this with gson and the libgdx json serializer and they both work the same way. 我尝试了gson和libgdx json序列化器,它们都以相同的方式工作。 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: (作为一种解决方法,我将列表存储为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. 但这并不是一个很好的解决方案,因为我必须自己在A中实现所有列表方法(如.add()、. get(),...)。 )

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();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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