【问题标题】:Add a property for each instance of a class in GSON在 GSON 中为类的每个实例添加一个属性
【发布时间】:2013-12-02 10:33:47
【问题描述】:
class Human {
   String name;
}

class Student extends Human {
   String college;
}

class Worker extends Human {
   String workPlace;
}

假设我想使用 GSON 序列化它。

是否可以为每个序列化的Student 实例添加一对"type" : "student"(就像type 是类的一个字段一样)?同样,为每个Worker 实例添加"type" : "worker"


关于此类 JSONS 的反序列化的相关问题: Deserialize recursive polymorphic class in GSON

【问题讨论】:

标签: java json serialization gson


【解决方案1】:

你可以像这样通过gson自定义JsonSerializer来做到这一点

public class HumanSerializer implements JsonSerializer<Human> {

 @Override
public JsonElement serialize(final Human human, final Type type, final JsonSerializationContext context) {
             final JsonObject json = new JsonObject();
             if(human instanceof Human)
                 json.addProperty("type", "Human");
             if(human instanceof Worker)
                 json.addProperty("type", "Worker");
             if(human instanceof Student)
                 json.addProperty("type", "Student");

         json.addProperty("name", human.getName());
        return json;
    }
}

最后你必须注册你的类然后序列化它

final GsonBuilder  gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Human.class,new  HumanSerializer());
gsonBuilder.registerTypeAdapter(Worker.class,new  HumanSerializer());
gsonBuilder.registerTypeAdapter(Student.class,new  HumanSerializer());
final Gson gson = gsonBuilder.create();

输出

 gson.toJson(new Worker("adam", "workplace"));
 gson.toJson(new Human("Jhon"));

{"type":"Worker","name":"adam"}
{"type":"Human","name":"Jhon"}

【讨论】:

  • 知道如何反序列化它吗?
  • 通过gson自定义反序列化器可以获取类型值。你有 HumanAdapater 也实现了 JsonDeserilize 最后填充你的对象并返回它
  • 你能举个例子让你的答案完整吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2020-09-01
  • 2020-08-05
相关资源
最近更新 更多