【发布时间】:2011-01-31 04:54:14
【问题描述】:
我正在考虑将 Google 的 GSON 用于我的 Android 项目,该项目将从我的网络服务器请求 JSON。返回的 JSON 将是...
1) 已知类型的成功响应(例如:“用户”类):
{
"id":1,
"username":"bob",
"created_at":"2011-01-31 22:46:01",
"PhoneNumbers":[
{
"type":"home",
"number":"+1-234-567-8910"
},
{
"type":"mobile",
"number":"+1-098-765-4321"
}
]
}
2.) 不成功的响应,将始终采用以下相同的基本结构。
{
"error":{
"type":"Error",
"code":404,
"message":"Not Found"
}
}
我希望 GSON 转换为正确的类型,具体取决于上述 error 键/值对的存在。我能想到的最实用的方法如下,但我很好奇是否有更好的方法。
final String response = client.get("http://www.example.com/user.json?id=1");
final Gson gson = new Gson();
try {
final UserEntity user = gson.fromJson(response, UserEntity.class);
// do something with user
} catch (final JsonSyntaxException e) {
try {
final ErrorEntity error = gson.fromJson(response, ErrorEntity.class);
// do something with error
} catch (final JsonSyntaxException e) {
// handle situation where response cannot be parsed
}
}
这实际上只是伪代码,因为在第一个捕获条件中,我不确定如何测试密钥 error 是否存在于 JSON 响应中。所以我想我的问题是双重的:
- 我可以/我如何使用 GSON 来测试密钥的存在,并据此决定如何解析?
- 这是其他处于类似情况的 GSON 正在做的事情,还是有更好的方法?
【问题讨论】: