我创建了 REST 服务,ExceptionEntity
如果出现问题,它会返回序列化的类。
如果应该反序列化的 jsonGson.fromJson()
类型不同,我想抛出一些异常。例如,我有这个应该反序列化的字符串(my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
但我使用Room
类作为这个序列化字符串的类型:
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?
[编辑] 我已经对此进行了测试,但它不起作用:
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);
}