20

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.

3
  • When you declare an int variable, its default value is 0. An int could not be null. So I advise you to use a String instead or to ignore the id value if it is 0. Commented Oct 28, 2014 at 10:22
  • @joao2fast4u I have edited my code friend Commented Oct 28, 2014 at 10:24
  • @Gunaseelan Check my answer for better solution. You no need to remove key after creating json. Commented Oct 28, 2014 at 10:38

5 Answers 5

25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

what if I have an Object as one of the properties of the class, and I have implemented Gson in that object?
3

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");

Comments

2
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

Comments

2

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.