Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson : Treat Empty String as null

I'm using gson to serialize a java object to json.

Gson gson = new GsonBuilder().serializeNulls().create();

This builder handles null values that's good. But along with this I want it to handle empty string also as null.

How can this be done?

like image 260
sahillearner Avatar asked Feb 09 '26 23:02

sahillearner


1 Answers

You will need to register a custom TypeAdapter that wraps the existing String TypeAdapter and replaces empty strings with JSON nulls.

Example code:

public static void main(String[] args) {
    Gson gson = createGson();
    System.out.println(gson.toJson(Arrays.asList("foo","bar","",null,"phleem")));
}

static Gson createGson() {
    return new GsonBuilder().serializeNulls()
                            .registerTypeAdapter(String.class,
                                                 new EmptyToNullTypeAdapter())
                            .create();

}

static class EmptyToNullTypeAdapter extends TypeAdapter<String> {

    @Override
    public void write(final JsonWriter out, final String value) throws IOException {
        if (value.isEmpty()) {
            out.nullValue();
        } else {
            TypeAdapters.STRING.write(out, value);
        }
    }

    @Override
    public String read(final JsonReader in) throws IOException {
        return TypeAdapters.STRING.read(in);
    }

}

Output:

["foo","bar",null,null,"phleem"]

Caveat

Finally: not sure this is a good idea, because it's an asymmetric solution, i.e. when you deserialize an object, and then serialize it again, your new object won't be equal to the original object (nulls instead of empty strings).

like image 115
Sean Patrick Floyd Avatar answered Feb 12 '26 14:02

Sean Patrick Floyd