JSONArray cannot be converted to JSONObject error

前端 未结 3 1088
醉酒成梦
醉酒成梦 2020-11-30 14:15

While fetching json data I am getting error:

JSONArray cannot be converted to JSONObject

Code for json generate:



        
相关标签:
3条回答
  • 2020-11-30 14:47

    Use this method:

    private void showJSON(String response) {
            list = new ArrayList<>();
            String name = null;
            try {
    
                JSONArray jsonObject = new JSONArray(response);
                for(int i = 0; i < jsonObject.length(); i++) {
                    JSONObject obj = jsonObject.getJSONObject(i);
                    //store your variable
                    list.add(obj.getString("Name"));
                }
    //            JSONArray result = jsonObject.getJSONArray("");
    //            JSONObject collegeData = result.getJSONObject(0);
    //            list.add(jsonObject.getString(collegeData.getString("Name")));
                Toast.makeText(getActivity(), name, Toast.LENGTH_LONG).show();
                city_list.addAll(list);
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
                // Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
            }
    
        }
    
    0 讨论(0)
  • 2020-11-30 14:49

    data is an array, not an object:

    JSONArray data = jsonObj.getJSONArray("data"); 
    
    0 讨论(0)
  • 2020-11-30 14:54

    Change

    JSONObject data = jsonObj.getJSONObject("data"); 
    

    to

    JSONArray data = jsonObj.getJSONArray("data");
    

    As value of data is JsonArray not JSONObject.

    And to Get individual Ids and Field Names, you should loop through this JSONArray, as follows:

    for(int i=0; i<data.length(); i++)
    {
         JSONObject obj=data.getJSONObject(i);
         String id = obj.getString("Id"); 
            String value = obj.getString("FieldName"); 
            Log.d("Item name: ", value);
    }
    
    0 讨论(0)
提交回复
热议问题