user1682133 user1682133 - 3 months ago 18
Android Question

JSONArray cannot be converted to JSONObject error

Hi while fetching json data am getting error JSONArray cannot be converted to JSONObject

pls help

code for json generate

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);


While reading the above json am getting errors
Any thing wrong with the code??

Answer

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);
}