Gson: Support for java.util.Optional

Created on 14 Jun 2017  路  5Comments  路  Source: google/gson

Usually, when I use Gson, I need to add special logic so that a field of Optional<X> gets serialized as X if it's present, and gets omitted if it's empty; and conversely on deserialization. This seems like the only reasonable way to handle Optional. Would you consider offering this feature (or accepting a PR that implements it)?

Most helpful comment

Gson can't depend on Java 8 types as it supports down to Java 6.

With Multi-Release JARs this would now be possible, at least for JRE >= 9.

All 5 comments

Gson can't depend on Java 8 types as it supports down to Java 6.

@JakeWharton So? It could always be in a separate module.

It looks like such a module exists: https://github.com/hsiafan/gson-java8-datatype
The errors emitted if you forget to include it are very confusing and do not obviously lead you to determining that you must install this module, but once you do, Optional types work fine.

really would like to see this. Coming from Swift, the use of Optional with JSON is very useful.

Gson can't depend on Java 8 types as it supports down to Java 6.

With Multi-Release JARs this would now be possible, at least for JRE >= 9.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GoogleCodeExporter picture GoogleCodeExporter  路  31Comments

JakeWharton picture JakeWharton  路  39Comments

adiantek picture adiantek  路  23Comments

kdehairy picture kdehairy  路  43Comments

kramer picture kramer  路  26Comments