GSON - 特定情况下的自定义序列化程序

Sté*_*tte 30 java serialization 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;
}
Run Code Online (Sandbox Code Playgroud)

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

{ "students": [{ 
                 "name":"name1",
                 "school": "1"          //the id of the scool, not its entire Json
              }],
  "school": [{                        //the entire JSON
              "id" : "1",
              "name": "schoolName"
            }]
}
Run Code Online (Sandbox Code Playgroud)

为此,我必须为学生部分使用自定义序列化程序,以便Gson只打印学校的ID.但是对于学校来说,我必须有正式的序列化器.

如何只用一个Gson对象做一切?

Jon*_*nas 50

您可以编写这样的自定义序列化程序:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


job*_*ert 32

当然,无论您要将此对象序列化,都需要将其添加到Gson中,如下所示:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Student.class, new StudentAdapter())
    .create();
return gson.toJson([YOUR_OBJECT_TO_BE_SERIALIZED]);
Run Code Online (Sandbox Code Playgroud)