tags:

views:

112

answers:

1

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.

A: 

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);
Konstantin Burov
I am sorry, I am a real newbie in this world. I can't seem to adapt your code to my needs. JSONArray array = null; String response = client.getResponse(); try { array = new JSONArray(response); } catch (JSONException e1) e1.printStackTrace(); } j = new JSONObject(array); ?? Do I need this anymore ? cats = gson.fromJson(j.toString(), TrackCategories.class); ??How does this change ? It trows an error on new JSONObject Thank you very much for your support.
Alin
well I'm not experienced with gson library. Probably try to add curve brackets - {your original json string} - to your json string, so that would become an object. Then use your original code.
Konstantin Burov