Create JSON String using GSON

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

    Better is to use @expose annotation like

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

    And use below method to get Json string from your object

    private String getJsonString(Student student) {
        // Before converting to GSON check value of id
        Gson gson = null;
        if (student.id == 0) {
            gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .create();
        } else {
            gson = new Gson();
        }
        return gson.toJson(student);
    }
    

    It will ignore id column if that is set to 0, either it will return json string with id field.

提交回复
热议问题