0

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:

  1. I want to serialize Option.none() as null in JSON, and Option.some("hello") as "hello", so that there is no redundancy (I'm assuming that the value inside Option.some is @NotNull).
  2. I'm also hoping that an Option<T> value keep not changed after serialize and deserialze.

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?

luochen1990
  • 3,689
  • 1
  • 22
  • 37
  • 1
    Does this answer your question? [How to serialize Optional classes with Gson?](https://stackoverflow.com/questions/12161366/how-to-serialize-optionalt-classes-with-gson) – Marcono1234 May 20 '20 at 09:31
  • @Marcono1234 Thanks! this post solves part of my question -- about the generic type, but dosn't answer my main question -- how to deserialize JsonNull with customized JsonDeserializer. – luochen1990 May 20 '20 at 10:49
  • See the answer with the most votes there, it shows how to implement it for `Optional` (for `Option` it should be pretty similar). Trying to implement this with `JsonDeserializer` will not work, see [my comment](https://github.com/google/gson/issues/1696#issuecomment-631358452) on your GitHub issue – Marcono1234 May 20 '20 at 11:42

0 Answers0