简体   繁体   中英

GSON - Custom serializer in specific case

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

Of course wherever you are going to serialize this object you need to add it to the Gson like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM