google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.16k stars 4.27k forks source link

Add support for Optional<T> in parsing instead of null #2644

Open spacey-sooty opened 4 months ago

spacey-sooty commented 4 months ago

Problem solved by the feature

Often when parsing their is the risk of null exceptions and more importantly it is hard to document a field being optional through the type signature.

Feature description

This feature would support using Optional for fields where if GSON cannot find the key it would give the none variant.

Marcono1234 commented 4 months ago

This is similar to #1005, or possibly a more specific duplicate of it. And related to #61.

Currently when a property is not present in the JSON data, Gson does not modify the field of the Java object and does not call the TypeAdapter. So if the field has type Optional but has an (implicit) default value of null, then Gson keeps that value.

As workaround you can initialize the field with a non-null default value, for example Optional<String> s = Optional.empty();. But you must make sure that the declaring class has a no-args constructor, otherwise this might not work, see [GsonBuilder.disableJdkUnsafe()](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html#disableJdkUnsafe()) for details.

spacey-sooty commented 4 months ago

Thanks for providing this work around. I have had a go using it but this actually won't work in the Optional case. I can provide the stacktrace if you would like but I am reasonably confident from reading through it that when I specify Optional<String> because it is an object GSON does not recognise it expects an object as opposed to a string and will throw an exception.

I like the idea of providing a more general solution here, but I think there could be some advantages to implicitly using the Optional.empty() default for fields typed Optional<T>. I think this would be a good way of providing explicit support for something being optional within the type of a field.

Marcono1234 commented 4 months ago

when I specify Optional<String> because it is an object GSON does not recognise it expects an object as opposed to a string and will throw an exception

Sorry, I should have mentioned that Gson has no built-in adapter for Optional yet (#1102) so you would have to write one yourself or use one from a third-party library, see also this Stack Overflow question.

spacey-sooty commented 4 months ago

Ok I'll do that, thanks for the help!