Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

java - Gson doesn't serialize fields defined in subclasses

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]
}

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).

How to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Gson 2.1 supports this out of the box:

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<A>();
    c.classes.add(new A(1));
    c.classes.add(new B(2, 3));
    System.out.println(gson.toJson(c));
  }

  static class A
  {
    int stars;

    A(int stars)
    {
      this.stars = stars;
    }
  }

  static class B extends A
  {
    int sunshines;

    B(int stars, int sunshines)
    {
      super(stars);
      this.sunshines = sunshines;
    }
  }

  static class C
  {
    List<A> classes;
  }
}

The ouput is

{
  "classes": [
    {
      "stars": 1
    },
    {
      "sunshines": 3,
      "stars": 2
    }
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...