Create JSON String using GSON

后端 未结 5 2075
梦毁少年i
梦毁少年i 2021-02-05 09:29

I am having a class like following,

public class Student {
    public int id;
    public String name;
    public int age;    
}

Now I want to c

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 09:31

    You should introduce additional field to Student class that will notice GSON about id serialization policy. Then, you should implement custom serializer that will implement TypeAdapter. In your TypeAdapter implementation according to id serialization policy you will serialize it or not. Then you should register your TypeAdapter in GSON factory:

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Student.class, new StudentTypeAdapter());
    

    Hope this helps.

提交回复
热议问题