GSON - Custom serializer in specific case

前端 未结 2 1071
心在旅途
心在旅途 2020-11-28 07:55

I have this schema :

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

public class School {
       public int id;
       pub         


        
相关标签:
2条回答
  • 2020-11-28 08:33

    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]);
    
    0 讨论(0)
  • 2020-11-28 08:39

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题