Gson不会序列化子类中定义的字段 [英] Gson doesn't serialize fields defined in subclasses

查看:45
本文介绍了Gson不会序列化子类中定义的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某些未知原因,如果我有:

For some unknown reason if I have:

class A{
int stars;
public int getStars(){
return stars;
}

public void setStarts(int stars){
this.stars = stars;
}
}

class B extends A{
 int sunshines;

[getter and setter for sunshines]
}

class C{
 List<A> classes;
[get and set for classes]
}

如果我序列化类型为C的对象,则在字段类的序列化对象中只有A的字段(而如果对象是B,我希望拥有B的字段).

if I serialize an Object of type C I have only the fields of A in the serialized objects in the field classes (while I would expect to have the fields of B if the object is a B).

该怎么做?

推荐答案

我已经尝试了您的示例,并在课堂上将 List< A> 替换为 List< Object> C解决了这个问题.

I've tried your example and replacing List<A> with List<Object> in class C solved this problem.

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonInheritanceTest {
public static void main(String[] args) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    C c = new C();
    c.classes = new ArrayList<Object>();
    c.classes.add(new A());
    c.classes.add(new B());
    System.out.println(gson.toJson(c));
}

public static class A {
    int stars;
}

public static class B extends A {
    int sunshines;
}

public static class C {
    List<Object> classes;
}
}

产生:

{
  "classes": [
    {
      "stars": 0
    },
    {
      "sunshines": 0,
      "stars": 0
    }
  ]
}

但是,这会阻止您使用默认的json反序列化...请考虑重构您的OOD和继承关系.

This, however, prevent you from using default json deserialization... Consider refactoring you OOD and inheritance relationships.

这篇关于Gson不会序列化子类中定义的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆