我已经创建了REST服务,ExceptionEntity如果出现问题,它会返回序列化的类.
如果应该反序列化的json Gson.fromJson()是不同的类型,我想抛出一些异常.例如,我有这个字符串应该反序列化(my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
Run Code Online (Sandbox Code Playgroud)
但我使用Roomclass作为此序列化字符串的类型:
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?
Run Code Online (Sandbox Code Playgroud)
[编辑] 我测试了这个,它不起作用:
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);
}
Run Code Online (Sandbox Code Playgroud)
Jac*_*ack 14
根据GSon 文档,如果根据您提供的类型无法反序列化json流,则会抛出异常:
抛出:
JsonParseException- 如果json不是classOfT类型的对象的有效表示
但是这是一个未经检查的异常,如果你想提供一个你应该尝试的自定义异常
try {
Room r = gson.fromJson(json, Room.class);
}
catch (JsonParseException e) {
throw new YourException();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21890 次 |
| 最近记录: |