0

我正在开发一个 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: WARN/System.err(568): org.json.JSONException: Value [{"Id":1,"CategoryName":"Food"},{"Id":2," org.json.JSONArray 类型的 CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{"Id":4,"CategoryName":"Work"}] 无法转换到 JSONObject 09-02 07:06:47.029: WARN/System.err(568): at 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;
 }

}

分类信息.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;
 }

}

要访问网络服务,我使用以下类: http: //lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

请帮助我,因为我现在被困了 2 天,不知道如何继续。我在这里找到了一些主题,但仍然没有找到解决方法。非常感谢。

4

1 回答 1

0

JSON 字符串中的顶级实体是 JSONArray 而不是 JSONObject,而您正在尝试将其解析为对象。从字符串创建一个数组并使用它。

JSONArray array = new JSONArray(response);
于 2010-09-02T08:37:16.667 回答