I'm now trying to customize the Serializer and Deserializer in Gson for Option<T>
(using io.vavr.control.Option
, or Optional<T>
if using java.utils.*
, which is similar here).
And there are 2 requirement for what I want:
- I want to serialize
Option.none()
asnull
in JSON, andOption.some("hello")
as"hello"
, so that there is no redundancy (I'm assuming that the value insideOption.some
is @NotNull). - I'm also hoping that an
Option<T>
value keep not changed afterserialize
anddeserialze
.
So, following is my try (here is the full code, and I'm referencing this post to solve the generic type issue):
public static class OptionJsonAdapter<T> implements JsonSerializer<Option<T>>, JsonDeserializer<Option<T>> {
private final Type typeOfT;
public OptionJsonAdapter(Type typeOfT) {
this.typeOfT = typeOfT;
}
@Override
public JsonElement serialize(Option<T> src, Type typeOfSrc, JsonSerializationContext context) {
if (src.isEmpty()) {
return JsonNull.INSTANCE;
} else {
return context.serialize(src.get(), typeOfT);
}
}
@Override
public Option<T> deserialize(JsonElement json, Type typeOfRes, JsonDeserializationContext context) {
if (json.isJsonNull()) {
return Option.none();
} else {
return Option.some(context.deserialize(json, typeOfT));
}
}
}
But, above code cannot deserialize JSON null
into Option.none()
, even I indeed write a if (json.isJsonNull())
branch, it seems that the logical branch of the if-true case is never reached, when deserializing JsonNull, Gson even havn't call our customized deserialize()
function.
So, how can I serialize and deserialize Option
as what I want?