If I have a simple object as follows:
String name;
String email;
int age;
boolean isDeveloper;
Then let's say JSON object received have values:
{"name":null,"email":null,"age":26,"isDeveloper":true}
When deserializing this JSON using GSON as default I have:
{"age":26,"isDeveloper":true}
But email field missing will cause a failure afterwards on my application so I want to add
email = null;
Serialize back to JSON and have only this field value as null. Also not ignoring any non null fields.
Other null values should not be added to the resulting JSON.
I tried deserializing with a default GSON builder then serializing with a GSON that allows null values as:
Gson gson = new GsonBuilder().serializeNulls().create();
Problem is: this will look all null/empty values from the object class and set them all
{"name":null,"email":null,"age":26,"isDeveloper":true}
How can I set email property null then serialize back to a JSON containing only this field as null without ignoring any other non null values?
I'm using gson v2.2.4
Here is example code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App
{
private class UserSimple {
public String name;
public String email;
public int age;
public boolean isDeveloper;
UserSimple(String name, String email, int age, boolean isDeveloper) {
this.name = name;
this.email = email;
this.age = age;
this.isDeveloper = isDeveloper;
}
}
public static void main( String[] args )
{
String userJson = "{'age':26,'email':'abc@dfg.gh','isDeveloper':true,'name':null}";
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
Gson gsonBuilder = new GsonBuilder().serializeNulls().create();
UserSimple deserializedObj = gson.fromJson(userJson, UserSimple.class);
System.out.println("\n"+gson.toJson(deserializedObj));
deserializedObj.email = null;
String serializedObj = gsonBuilder.toJson(deserializedObj, UserSimple.class);
System.out.println("\n"+serializedObj);
}
}