Utworzono usługę REST, która zwraca ExceptionEntity
zserializowaną klasę, jeśli coś poszło nie tak.Gson.fromJson() - throw Wyjątek, jeśli typ jest inny
Chcę rzucić wyjątek, jeśli json, który powinien być deserialized przez Gson.fromJson()
jest w innym typie. Na przykład mam ten ciąg, który powinien być rozszeregować (my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
ale używam Room
klasy jako typ na ten serializowanym wyrażenie:
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?
[edytuj] Przetestowałem to i to nie działa:
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);
}
możliwym duplikatu [niech Gson rzucać wyjątki dotyczące niewłaściwych typów] (http://stackoverflow.com/questions/ 14242 236/let-gson-throw-exceptions-on-wrong-types) –