Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson.fromJson() - throw Exception if Type is different

Tags:

java

gson

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);
}
like image 761
pepuch Avatar asked Mar 25 '13 17:03

pepuch


1 Answers

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();
}
like image 68
Jack Avatar answered Oct 15 '22 20:10

Jack