android - JSONArray 无法转换为 JSONObject 错误

标签 android json parsing

获取 json 数据时出现错误:

JSONArray cannot be converted to JSONObject

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

在读取上面的 json 时出现错误 代码有什么问题吗??

最佳答案

改变

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

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

因为数据的值是 JsonArray 而不是 JSONObject。

要获取单独的 ID 和字段名称,您应该循环遍历此 JSONArray,如下所示:

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

关于android - JSONArray 无法转换为 JSONObject 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12559612/

相关文章:

java - 如何编译 AndEngine 源代码?

Android Listview float 第一行

android - 如何将 SMS 和 MMS 分类在一起?

python - 我如何用 Python 解析 GeoJSON

JAVA SAX解析错误

android - Android 中的马赛克位图

perl - 这些 JSON 命令有什么区别?

ios - 如果 json 数组中的某个值返回 null,如何返回下一个非 null json 值?

javascript - 以编程方式构造对象数组

Java jsoup 链接忽略