[Discussion] Deprecate non-type-safe `Gson.fromJson(..., Type)` overloads
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
# Problem solved by the feature
The `Gson.fromJson(..., Type)` overloads are non-type-safe because the type parameter `T` used for the return type is not bound by any of the parameters. This makes it easy to accidentally introduce bugs without noticing them immediately and only later at a completely unrelated location experiencing a `ClassCastException`. For example:
```java
Type type = new TypeToken>() {}.getType();
List list = new Gson().fromJson("[1, 2]", type);
// ClassCastException: class Integer cannot be cast to class String
System.out.println("First value: " + list.get(0));
```
The sample code above does not produce any compiler warnings; the issue here is that `type` (`List`) does not match the expected return type of `fromJson` (`List`).
This basically affects all methods which will get the `TypeParameterUnusedInFormals` Error Prone suppression. This also affects `JsonDeserializationContext.deserialize`, see #2216.
# Feature description
Deprecate all `fromJson(..., Type)` overloads. The deprecation comment should:
- explain why the methods are unsafe
- refer to the overload with `TypeToken` parameter (introduced by #1700)
- mention migration paths
- passing around `TypeToken` instead of `Type` in user code (e.g. as method arguments and field values)
- if necessary converting `Type` to `TypeToken` with `TypeToken.get(Type)`, but then it is the user's responsibility to make sure the code is safe
- if necessary obtaining `Type` from `TypeToken` by calling `TypeToken.getType()` (this should be relatively cheap since the method is just a plain getter method)
There is however no need to remove the deprecated methods then, they could probably stay there 'indefinitely'.
# Risks
This might cause a lot of deprecation noise for users because until recently (see #1700) the overloads with `TypeToken` parameter did not exist yet, so most code probably still uses `fromJson(..., Type)`. Though on the other hand this might increase awareness that the code of the users is potentially unsafe or even incorrect which they just did not notice yet.
Maybe it should also be investigated (if that is possible) how often users run into this issue compared to other issues, mainly `TypeToken` capturing type-erased type parameters, see #1219.
# Alternatives / workarounds
Do nothing, and risk that users keep running into difficult to debug `ClassCastException`s.
Contributor guide
Assessment
This issue has not been assessed yet.