2

I execute async request (REST query). Getting response from server side is...

[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}]

I need to parse response string to JSONObject and then to

ArrayList<Map<String, String>>

In my next async method of getting data (some code is commented):

//async getting data
@Override
public void onSuccessResult(String response) {
    String message;
    Log.d(Constants.LOG, response);
    try {
        JSONObject jsonResponse = new JSONObject(response);

/*
            JSONArray jsonArray = jsonResponse.getJSONArray("id");
            data.clear();
            for(int i=0;i<jsonArray.length()-1;i++){
                HashMap<String, String> m = new HashMap<String, String>();
                JSONArray url = jsonArray.getJSONArray(i);
                m.put("name", url.getString(0));
                dataPlants.add(m);

            //sAdapter.notifyDataSetChanged();

*/

    }catch (JSONException e) {
        Log.d(Constants.LOG, e.toString());
        e.printStackTrace();
    }

I get the next exception:

org.json.JSONException: Value
[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}] of type org.json.JSONArray cannot be converted to JSONObject

So, how to proceed response appropriately

1 Answer 1

2

The problem comes from the fact that you are trying to create a JSONObject from a String that represents a JSONArray
You need to parse the String as JSONArray.

JSONObject jsonResponse = new JSONObject(response);

should be

JSONArray jsonResponse = new JSONArray(response);

in

 jsonResponse = new JSONArray(response);
 //data.clear();
 for (int i = 0; i < jsonResponse.length(); i++) {
     Object obj = jsonResponse.get(i);
     if(obj instanceof JSONObject) {
          HashMap<String, String> m = new HashMap<>();
          JSONObject object = jsonResponse.getJSONObject(i);
          m.put(object.getString("id"), object.getString("name"));
          dataPlants.add(m);
     }
 }
 //sAdapter.notifyDataSetChanged();

@ Edit : Additionally, I editted the code so there is an object verification there.
Honestly, whenever treating with JSON files, you should treat them as objects and check whether they are an instance of a JSONObject or an instance of a JSONArray, since both have different parsing mechanisms

1
  • @Maksim Good to know that it worked! Mark the answer as accepted so others may find it useful for fixing their bugs. Regards Aug 11, 2016 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.