Android – jsonarray cannot be converted to jsonobject error

When getting JSON data, I received an error:

Code to generate JSON:

JSONObject parent = new JSONObject();
DatabaseHandler dbh = new DatabaseHandler(getApplicationContext());  
            for(int i=0; i < allEds.size(); i++){
                String edsText = allEds.get(i).getText().toString();                                           
               //spinner = allSpns.get(i);
               String spinSelected=allSpns.get(i).getSelectedItem().toString();                  
               try
                {
                   JSONObject json = new JSONObject();          
                   json.put("Id", i);
                   json.put("FieldName", edsText);
                   json.put("FieldType",spinSelected);
                   parent.accumulate("data", json);



                }
                catch (JSONException e)
                {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }                   

            }
Generated json is   
            {"data":
[{"FieldType":"Account Number","FieldName":"r","Id":0},
  {"FieldType":"Net      Banking Id","FieldName":"tt","Id":1}
 ]}
code for json read
------------------
JSONObject jsonObj = new JSONObject(folderStructure);
        JSONObject data = jsonObj.getJSONObject("data"); 
        String id = data.getString("Id"); 
        String value = data.getString("FieldName"); 
        Log.d("Item name: ", value);    

What's wrong with the error code when reading the JSON above?

resolvent:

change

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

to

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

Because the value of the data is jsonarray instead of jsonobject

To get a single ID and field name, you should traverse 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);
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>