Skip to content

Apply serialize nulls for specific classes only #913

@bradroid

Description

@bradroid

I want a Gson setup in which nulls are not serialized by default. I want nulls to be serialized for certain class only. This is how I tried to solve it, but it does not work as expected.

This is how a gson instance is created, used for general serialization/deserialization for all API requests app needs to make:

 @Provides
 Gson provideGson() {
        GsonBuilder builder = new GsonBuilder()
                .registerTypeAdapter(SubmitBody.class, new SubmitBodySerializer();
        return builder.create();
    }

I want to make SubmitBody class an exception for serialization, I want null fields from this class to be serialized as Json nulls, unlike rest of the classes where such fields will be ignored. That's why I registered a custom serializer for this class that looks like this:

public class SubmitBodySerializer implements JsonSerializer<SubmitBody> {

    public SubmitBodySerializer(Gson gson) {
        this.gson = new GsonBuilder().serializeNulls().create();
    }

    @Override
    public JsonElement serialize(SubmitBody src, Type typeOfSrc, JsonSerializationContext context) {
        return gson.toJsonTree(src);
    }
}

Within this class I use a separate Gson instance which serializes nulls. I can see that serialize method returns correct JsonElement with serialized nulls, however, when I check the Json body sent to the API, nulls are nowhere to be found, as if they are ignored.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions