-
Notifications
You must be signed in to change notification settings - Fork 4.3k
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:
Type type = new TypeToken<List<Integer>>() {}.getType();
List<String> 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<Integer>
) does not match the expected return type of fromJson
(List<String>
).
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 Add Gson.fromJson(..., TypeToken) overloads #1700) - mention migration paths
- passing around
TypeToken
instead ofType
in user code (e.g. as method arguments and field values) - if necessary converting
Type
toTypeToken
withTypeToken.get(Type)
, but then it is the user's responsibility to make sure the code is safe - if necessary obtaining
Type
fromTypeToken
by callingTypeToken.getType()
(this should be relatively cheap since the method is just a plain getter method)
- passing around
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.