Question

I am developing an Android application and I access a RESTfull web service that returns a JSON. This JSON I want to put it in POJOs but I think I am missing something as it doesn't work.

The JSON retuned is as follow:

[{"CategoryName":"Food","Id":1},{"CategoryName":"Car","Id":2},{"CategoryName":"House","Id":3},{"CategoryName":"Work","Id":4}]

this is returned in response variable

  String response = client.getResponse();

And now I try the following:

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();
}

The error I get is:

09-02 07:06:47.009: WARN/System.err(568): org.json.JSONException: Value [{"Id":1,"CategoryName":"Food"},{"Id":2,"CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{"Id":4,"CategoryName":"Work"}] of type org.json.JSONArray cannot be converted to JSONObject 09-02 07:06:47.029: WARN/System.err(568): at org.json.JSON.typeMismatch(JSON.java:107)

Here are the POJO objects 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;
 }

}

To access the web service I use the class from: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

Please help me as I am stuck for 2 days now and can't figure out how to continue. I found some subjects here but still didn't found a way around. Thank you very much.

Was it helpful?

Solution

Top level entity in your JSON string is JSONArray not JSONObject, while you're trying to parse it as object. Create an array from the string and use that.

JSONArray array = new JSONArray(response);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top