Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...