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

I created a REST service that returns an ExceptionEntity serialized class as a result if something went wrong.

I want to make some kind of exception if the json that should be deserialized by Gson.fromJson() is of a different type. For example, I have this line that needs to be deserialized (my.ExceptionEntity.class):

 {"exceptionId":2,"message":"Room aaaa already exists."} 

but I use the Room class as the 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 tested this and it does not 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); } 
+7
source share
1 answer

According to the GSon documentation, an exception is already thrown if the json stream cannot be deserialized according to the type you specified:

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(); } 
+9
source

All Articles