Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Default value to a variable when deserializing using gson

Tags:

java

json

gson

I am trying to convert JSON to Java object. When a certain value of a pair is null, it should be set with some default value.

Here is my POJO:

public class Student {           String rollNo;     String name;     String contact;     String school;      public String getRollNo() {         return rollNo;     }     public void setRollNo(String rollNo) {         this.rollNo = rollNo;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getSchool() {         return school;     }     public void setSchool(String school) {         this.school = school;     } } 

Example JSON object:

{   "rollNo":"123", "name":"Tony", "school":null } 

So if school is null, I should make this into a default value, such as "school":"XXX". How can I configure this with Gson while deserializing the objects?

like image 786
Arun Avatar asked May 13 '15 13:05

Arun


People also ask

Does GSON use default constructor?

If there is a default/no-argument constructor, it is called, otherwise, Gson calls no constructor at all.

Is GSON better than JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.

What does GSON toJson do?

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

If the null is in the JSON, Gson is going to override any defaults you might set in the POJO. You could go to the trouble of creating a custom deserializer, but that might be overkill in this case.

I think the easiest (and, arguably best given your use case) thing to do is the equivalent of Lazy Loading. For example:

private static final String DEFAULT_SCHOOL = "ABC Elementary"; public String getSchool() {     if (school == null) school == DEFAULT_SCHOOL;     return school; } public void setSchool(String school) {     if (school == null) this.school = DEFAULT_SCHOOL;     else this.school = school; } 

Note: The big problem with this solution is that in order to change the Defaults, you have to change the code. If you want the default value to be customizable, you should go with the custom deserializer as linked above.

like image 168
durron597 Avatar answered Sep 17 '22 15:09

durron597


I think that the way to do this is to either write your no-args constructor to fill in default values, or use a custom instance creator. The deserializer should then replace the default values for all attributes in the JSON object being deserialized.

like image 33
Stephen C Avatar answered Sep 18 '22 15:09

Stephen C