JSONArray 无法转换为 JSONObject 错误 [英] JSONArray cannot be converted to JSONObject error
本文介绍了JSONArray 无法转换为 JSONObject 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在获取 json 数据时出现错误:
While fetching json data I am getting error:
JSONArray 无法转换为 JSONObject
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 时出现错误代码有什么问题吗??
While reading the above json am getting errors Any thing wrong with the code??
推荐答案
更改
JSONObject data = jsonObj.getJSONObject("data");
到
JSONArray data = jsonObj.getJSONArray("data");
因为数据的值是 JsonArray 而不是 JSONObject.
As value of data is JsonArray not JSONObject.
要获取单个 Id 和字段名称,您应该循环遍历此 JSONArray,如下所示:
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);
}
这篇关于JSONArray 无法转换为 JSONObject 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文