Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON String using GSON

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.

like image 289
Gunaseelan Avatar asked Oct 28 '14 10:10

Gunaseelan


People also ask

Can we convert String to JSON in Java?

There are the following three libraries are used to convert String to JSON Object in Java: Using Gson Library. Using JSON-Simple Library. Jackson Library.

What is the difference between JSON and GSON?

The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.


2 Answers

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.

like image 74
Pankaj Kumar Avatar answered Oct 18 '22 22:10

Pankaj Kumar


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");
like image 44
stacky Avatar answered Oct 18 '22 21:10

stacky