How to return only one specific null field with GSON?

Shell_Leko :

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':'[email protected]','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);


    }
}
mnj11 :

You could create your own custom adapter to resolve the issue at hand :

class MyCustomTypeAdapter extends TypeAdapter<UserSimple> {
    @Override
    public void write(JsonWriter writer, UserSimple userSimple) throws IOException {
        writer.beginObject();
        if(userSimple.getName() != null){
            writer.name("name");
            writer.value(userSimple.getName());
        }

        // you want to include email even if it's null
        writer.name("email");
        writer.value(userSimple.getEmail());

        if(userSimple.getAge() != null){
            writer.name("age");
            writer.value(userSimple.getAge());
        }
        if(userSimple.getDeveloper() != null){
            writer.name("isDeveloper");
            writer.value(userSimple.getDeveloper());
        }
        writer.endObject();
    }

    public UserSimple read(JsonReader reader) throws IOException {
    // you could create your own
        return null;
    }
} 

Input :

String userJson = "{'age':null,'email':null,'isDeveloper':true,'name':'somename'}";

Output :

serializedObj :{"name":"somename","email":null,"isDeveloper":true}

Input :

String userJson = "{'age':20,'email':null,'isDeveloper':true,'name':'somename'}";

Output :

serializedObj :{"name":"somename","email":null,"age":20,"isDeveloper":true}

Have a look at https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91438&siteId=1