GSON - 在特定情况下使用自定义序列化器

41

我有这个模式:

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对象,并得到类似下面的内容:

{ "students": [{ 
                 "name":"name1",
                 "school": "1"          //the id of the scool, not its entire Json
              }],
  "school": [{                        //the entire JSON
              "id" : "1",
              "name": "schoolName"
            }]
}
为了做到这一点,我必须使用针对学生部分的自定义序列化器,以便Gson仅打印School的id。但是对于School,我必须有一个普通的序列化器。
如何只使用一个Gson对象来完成所有操作?
2个回答

68

你可以编写一个自定义序列化器,类似于以下代码:

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

好的,我会这样做,即使有很多字段和只有一个外键,也会有点无聊... - Stéphane Piette

41
当然,无论你想要在哪里序列化这个对象,你都需要像这样将它添加到Gson中:
Gson gson = new GsonBuilder()
    .registerTypeAdapter(Student.class, new StudentAdapter())
    .create();
return gson.toJson([YOUR_OBJECT_TO_BE_SERIALIZED]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接