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

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

问题描述

我有这个模式:

  public class Student {
public String name;
公立学校;
}

public class School {
public int id;
公共字符串名称;
}
public class Data {
public ArrayList< Student>学生们;
public ArrayList< School>学校;
}

我想用Gson序列化Data对象,并得到如下所示的内容:

  {students:[{
name:name1,
school :1//该scool的id,而不是它的整个Json
}],
school:[{//整个JSON
id:1,
name:schoolName
}]
}

为了达到这个目的,我必须为学生部分使用自定义序列化程序,以便Gson只打印学校的ID。但是对于学校来说,我必须有正常的序列化程序。



我怎样才能用一个Gson对象做所有事情?



  public class StudentAdapter  

实现了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;
}
}


I have this schema :

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

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

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.

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天全站免登陆