Create JSON String using GSON

最后都变了- 提交于 2021-02-06 08:40:09

问题


I am having a class like following,

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

Now I want to create new Student,

//while create new student
Student stu = new Student();
stu.age = 25;
stu.name = "Guna";
System.out.println(new Gson().toJson(stu));

This gives me the following output,

{"id":0,"name":"Guna","age":25} //Here I want string without id, So this is wrong

So here I want String like

{"name":"Guna","age":25}

If I want to edit old Student

//While edit old student
Student stu2 = new Student();
stu2.id = 1002;
stu2.age = 25;
stu2.name = "Guna";
System.out.println(new Gson().toJson(stu2));

Now the output is

{"id":1002,"name":"Guna","age":25} //Here I want the String with Id, So this is correct

How can I make a JSON String with a field [At some point], without a field [at some point].

Any help will be highly appreciable.

Thanks.


回答1:


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.




回答2:


You can explore the json tree with gson.

Try something like this :

gson.toJsonTree(stu1).getAsJsonObject().remove("id");

You can add some properties also :

gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100");



回答3:


JsonObject jsObj =  (JsonObject) new Gson().toJsonTree(stu2);
jsObj.remove("age"); // remove field 'age'
jsObj.addProperty("key", "value"); // add field 'key'

System.out.println(jsObj);

You can manipulate with JsonObject




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/26605763/create-json-string-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!