Ho creato il servizio REST che restituisce la classe serializzata ExceptionEntity
come risultato se qualcosa è andato storto.Gson.fromJson() - genera Eccezione se Tipo è diverso
Voglio lanciare qualche eccezione se JSON che dovrebbe essere deserializzato da Gson.fromJson()
è di tipo diverso. Per esempio io ho questa stringa che dovrebbe essere deserializzato (my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
ma io uso Room
classe come tipo per questa stringa serializzata:
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] ho provato questo e non funziona:
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);
}
possibile duplicato del [lasciare GSON gettare eccezioni tipi sbagliati] (http://stackoverflow.com/questions/ 14242 236/let-gson-throw-exceptions-on-wrong-types) –