I've created REST service which returns ExceptionEntity
serialized class as a result if something gone wrong.
I want to throw some exception if json which should be deserialized by Gson.fromJson()
is in different type. For example I've got this string which should be deserialized (my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
but I use Room
class as type for this serialized string:
String json = "{\"exceptionId\":2,\"message\":\"Room aaaa already exists.\"}";
Room r = gson.fromJson(json, Room.class);
// as a result r==null but I want to throw Exception; how?
[EDIT] I've tested this and it doesn't work:
try {
return g.fromJson(roomJson, new TypeToken<Room>(){}.getType());
// this also doesn't work
// return g.fromJson(roomJson, Room.class);
} catch (JsonSyntaxException e) {
pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class);
throw ExceptionController.toGameServerException(ex);
} catch (JsonParseException e) {
pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class);
throw ExceptionController.toGameServerException(ex);
}
According to GSon documentation an exception is already thrown if the json stream can't be deserialized according to the type you provided:
Throws:
JsonParseException
- if json is not a valid representation for an object of type classOfT
But this is an unchecked exception, if you want to provide a custom exception you should try with
try {
Room r = gson.fromJson(json, Room.class);
}
catch (JsonParseException e) {
throw new YourException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With