You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Such construction works until we add Deserializer:
Gson badGson = new GsonBuilder()
.registerTypeAdapter(User.class, new UserBadDeserializer())
.create();
class UserBadDeserializer implements JsonDeserializer<User> {
@Override
public User deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
if (!jsonObject.has("name"))
throw new JsonParseException("json should contain the name field!");
String name = jsonObject.get("name").getAsString();
return new User(name);
}
}
The signature of deserialize method we should override, throws another
exception - JsonParseException, which is parent to JsonSyntaxException
and isn't caught by try-catch construction above
It flies further and may cause unexpected behaviour.
Its seems changing it T _com.google.gson.JsonDeserializer.deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonSyntaxException is the best option.
This is a bit related to #2359 (and other issues as well); Gson is currently not that consistent regarding which exception is thrown when.
The description of JsonSyntaxException sounds (at least to me) like it is mainly intended for actual malformed JSON. But there can be other cases where it necessary to throw an exception, for example an unexpected JSON null or a missing property. In those cases it might be more appropriate to throw a JsonParseException?
There are also cases where Gson itself is throwing a JsonParseException, see ToNumberPolicy or ReflectiveTypeAdapterFactory.
So maybe rather the Gson#fromJson methods should mention that JsonParseException can be thrown.
(This is just my personal opinion on this though. I don't know the original intentions for JsonParseException and JsonSyntaxException.)
Gson version
I found a bug in GSON library. It's actual fo version 2.12.1
Description
Bug description:
Method fromJson signature looks like that:
so, it's obvious to coders to catch JsonSyntaxException:
Such construction works until we add Deserializer:
The signature of deserialize method we should override, throws another
exception - JsonParseException, which is parent to JsonSyntaxException
and isn't caught by try-catch construction above
It flies further and may cause unexpected behaviour.
Solution 1 : Change signature of deserialize method to throw JsonSyntaxException.
Solution 2 : Change signature of fromJson method (and other methods calling
deserialize) to throw JsonParseException.
I've made a simple example to show this bug:
https://github.com/DGorokhov123/gson-bug
(С) Dmitriy Gorokhov [email protected], @DGorokhov123
The text was updated successfully, but these errors were encountered: