【发布时间】:2014-07-09 06:04:25
【问题描述】:
我有 JSONArray 具有以下结构:
{
"People":[
{
"006MST21IND":{
"desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP",
"attribute":"1,b_“F”ELEMENT / c_`G' ELEMENT;2,b_“F”ELEMENT / c_`G' ELEMENT;3, b_“F”ELEMENT / c_`G' ELEMENT"
}
},
{
"006MST22IND":{
"desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP",
"attribute":"1,b_“F”ELEMENT / c_`G' ELEMENT;2,b_“F”ELEMENT / c_`G' ELEMENT;3, b_“F”ELEMENT / c_`G' ELEMENT"
}
}
]
}
我正在尝试,但它给出了以下异常,
org.json.JSONException: Value [{"006MST21IND":{"attribute":"1,b_�F�ELEMENT \/ c_`G' ELEMENT;2,b_�F�ELEMENT \/ c_`G' ELEMENT;3, b_�F�ELEMENT \/ c_`G' ELEMENT","desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP"}},{"006MST22IND":{"attribute":"1,b_�F�ELEMENT \/ c_`G' ELEMENT;2,b_�F�ELEMENT \/ c_`G' ELEMENT;3, b_�F�ELEMENT \/ c_`G' ELEMENT","desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP"}}]
at People of type org.json.JSONArray cannot be converted to JSONObject
代码是:
我将 json 数据保存在文件中并从中获取,
File root = Environment.getExternalStorageDirectory();
File jsonFile = new File(root, "jsonFile.txt");
FileInputStream stream;
String jsonStr = null;
stream = new FileInputStream(jsonFile);
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.defaultCharset().decode(bb).toString();
stream.close();
然后通过使用该 jsonStr,我正在使用以下逻辑...
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObj1 = jsonObj.getJSONObject("People");
JSONArray myJson=jsonObj1.getJSONArray("006MST21IND");
if (myJson!=null && myJson.length()!=0) {
for(int i=0;i<myJson.length();i++)
{
JSONObject obj2 = myJson.getJSONObject(i);
desc = obj2.getString("desc");
attribute = obj2.getString("attribute");
Log.e("Desc:", desc);
Log.e("Attribute:", attribute);
}
}
我尝试过但失败了。
【问题讨论】:
-
难以阅读编辑您的问题
-
使用 try {} catch ().. 并尝试调试.. 在哪一行出现错误.. 看到错误.. 你会很容易理解你是关键字解析为“JSONArray”或“JSONObject”
-
我认为您正在获取 jsonarray 作为响应,但您正在尝试将其转换为 jsonobject..请检查响应
-
它明确指出
People of type org.json.JSONArray cannot be converted to JSONObject。 -
正如@Marius 所说,错误很明显。您可能想使用json.parser.online.fr 来帮助解析 JSON。有一些很酷的功能,例如“选项”中的“显示 JS 类型”)。
标签: android parsing android-json jsonexception