GSON - 特定情况下的自定义序列化程序 [英] GSON - Custom serializer in specific case

查看:24
本文介绍了GSON - 特定情况下的自定义序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个架构:

public class Student {
       public String name;
       public School school;
}

public class School {
       public int id;
       public String name;
}
public class Data {
      public ArrayList<Student> students;
      public ArrayList<School> schools;
}

我想用 Gson 序列化 Data 对象,并得到类似的东西:

I would like to serialize the Data object with Gson, and get something like :

{ "students": [{ 
                 "name":"name1",
                 "school": "1"          //the id of the scool, not its entire Json
              }],
  "school": [{                        //the entire JSON
              "id" : "1",
              "name": "schoolName"
            }]
}

为了做到这一点,我必须为学生部分使用自定义序列化程序,以便 Gson 只打印学校的 id.但是对于学校,我必须有正常的序列化程序.

To make that, I must use custom serializer for the student part, so that Gson only print the id of the School. But for the School, I have to have nomal serializer.

如何只用一个 Gson 对象做所有事情?

How can I do everything with only one Gson object ?

推荐答案

你可以像这样编写自定义序列化器:

You can write a custom serializer something like this:

public class StudentAdapter implements JsonSerializer<Student> {

 @Override
 public JsonElement serialize(Student src, Type typeOfSrc,
            JsonSerializationContext context) {

        JsonObject obj = new JsonObject();
        obj.addProperty("name", src.name);
        obj.addProperty("school", src.school.id);

        return obj;
    }
}

这篇关于GSON - 特定情况下的自定义序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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