I want to serialize nulls for a specific field or class.
In GSON, the option serializeNulls()
applies to the whole JSON.
Example:
class MainClass {
public String id;
public String name;
public Test test;
}
class Test {
public String name;
public String value;
}
MainClass mainClass = new MainClass();
mainClass.id = "101"
// mainClass has no name.
Test test = new Test();
test.name = "testName";
test.value = null;
mainClass.test = test;
Creating JSON using GSON:
GsonBuilder builder = new GsonBuilder().serializeNulls();
Gson gson = builder.create();
System.out.println(gson.toJson(mainClass));
Current ouput:
{
"id": "101",
"name": null,
"test": {
"name": "testName",
"value": null
}
}
Desired output:
{
"id": "101",
"test": {
"name": "testName",
"value": null
}
}
How to achieve the desired output?
Preferred solution would have the following properties:
- Do NOT serialize nulls by default,
- Serialize nulls for fields with a specific annotation.