简体   繁体   中英

How to proceed rest response to JSON

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM