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.
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: