6

获取 json 数据时出现错误:

JSONArray 无法转换为 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 时出现错误代码有什么问题吗?

4

3 回答 3

13

改变

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);
}
于 2012-09-24T06:08:05.150 回答
3

使用此方法:

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

    }
于 2017-10-11T07:04:23.497 回答
0

data是一个数组,而不是一个对象:

JSONArray data = jsonObj.getJSONArray("data"); 
于 2012-09-24T06:10:25.853 回答