Create JSON String using GSON

后端 未结 5 2015
梦毁少年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:39

    You have two options.

    • Use Java's transient keyword which is to indicate that a field should not be serialized. Gson will exclude it automatically. This may not work for you as you want it conditionally.

    • Use @Expose annotation for the fields that you want and initialize your Gson builder as following:

      Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    So you need to mark name and age fields using @Expose and you need to have two different Gson instances for the default one which includes all fields and the one above which excludes fields without @Expose annotation.

提交回复
热议问题