google / google/gson

Apply serialize nulls for specific classes only

Open
#913 3 comments 3 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

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 {

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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.