简体   繁体   中英

Gson TypeAdapter and serializeNulls

I'm using Gson 2.4.

Gson has a flag whether null values should be serialized or omitted (the default). When I create a TypeAdapter from a Gson which omits nulls and serialize an object via the TypeAdapter then this flag is ignored, contradicting the Javadoc :

Type adapters should be prepared to read null from the stream and write it to the stream. (...) If your Gson instance has been configured to GsonBuilder.serializeNulls(), these nulls will be written to the final document. Otherwise the value (and the corresponding name when writing to a JSON object) will be omitted automatically. In either case your type adapter must handle null.

Here is a test which demonstrates the problem:

import com.google.gson.Gson;

public class Test {
    private String name;

    public static void main(String[] args) throws Exception {
        Test object = new Test();
        Gson gson = new Gson(); // serializeNulls is off by default

        System.out.println(gson.toJson(object));
        System.out.println(gson.getAdapter(Test.class).toJson(object));
    }
}

This prints:

{}
{"name":null}

I expected that the second line is {} .

Is this a bug or did I misread the documentation? In both cases: Is there are a workaround to omit nulls when serializing via a TypeAdapter ?

A TypeAdapter doesn't do the actual raw serialization. It defers to a JsonWriter which it receives in its write method. So the actual check for null is done in the JsonWriter 's various name / value calls (for JSON objects).

The JsonWriter maintains a serializeNulls flag (among others). When using Gson#toJson , the Gson object will create a new JsonWriter and overwrite its serializeNulls value with its own and pass that JsonWriter to whatever TypeAdapter it decides to use.

In your second case, the TypeAdapter#toJson call is creating a new JsonWriter with default values. The javadoc of JsonWriter#setSerializeNulls states

Sets whether object members are serialized when their value is null. This has no impact on array elements. The default is true .

That's the behavior you see.

You could create your own JsonWriter and configure it appropriately and pass it to the overloaded toJson(Writer, T) method.

I think the javadoc statement applies to the use of TypeAdapter objects through Gson objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM