【发布时间】:2010-09-02 07:24:13
【问题描述】:
我正在开发一个 Android 应用程序并访问一个返回 JSON 的 RESTfull Web 服务。这个 JSON 我想把它放在 POJO 中,但我认为我遗漏了一些东西,因为它不起作用。
返回的 JSON 如下:
[{"CategoryName":"Food","Id":1},{"CategoryName":"Car","Id":2},{"CategoryName":"House","Id":3 },{"CategoryName":"Work","Id":4}]
这是在响应变量中返回的
String response = client.getResponse();
现在我尝试以下方法:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
MainCategories cats = null;
try
{
j = new JSONObject(response);
cats = gson.fromJson(j.toString(), MainCategories.class);
}
catch(Exception e)
{
e.printStackTrace();
}
我得到的错误是:
09-02 07:06:47.009: 警告/系统错误(568): org.json.JSONException:值 [{"Id":1,"CategoryName":"Food"},{"Id":2,"CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{ "Id":4,"CategoryName":"工作"}] org.json.JSONArray 类型的不能是 转换为 JSONObject 09-02 07:06:47.029: 警告/System.err(568):在 org.json.JSON.typeMismatch(JSON.java:107)
这里是 POJO 对象 MainCategories.java
public class MainCategories {
private List<CategoryInfo> category;
public List<CategoryInfo> getCategory() {
if (category == null) {
category = new ArrayList<CategoryInfo>();
}
return this.category;
}
}
CategoryInfo.java
public class CategoryInfo {
public String categoryName;
public Integer id;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String value) {
this.categoryName = ((String) value);
}
public Integer getId() {
return id;
}
public void setId(Integer value) {
this.id = value;
}
}
要访问 Web 服务,我使用来自以下位置的类:http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
请帮助我,因为我现在被困了 2 天,不知道如何继续。我在这里找到了一些主题,但仍然没有找到解决方法。非常感谢。
【问题讨论】: