使用Java解码对象的JSON数组 [英] Using Java to decode JSON array of objects
本文介绍了使用Java解码对象的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的JSON如下:
[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
它是一个对象数组.
我需要使用Java对其进行解析.我在使用图书馆: http://code.google.com/p/json-simple/downloads/list
I need to parse it using Java. I am using the library at : http://code.google.com/p/json-simple/downloads/list
此链接上的示例1大致符合我的要求: http://code.google.com/p/json-simple/wiki/DecodingExamples
Example 1 at this link approximates what I require: http://code.google.com/p/json-simple/wiki/DecodingExamples
我有以下代码:
/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)
Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
try {
jsonObj = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2: " + jsonObj.get("1"));
} catch (JSONException e) {
e.printStackTrace();
}
}
我遇到以下异常:
java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
有人可以帮忙吗?
谢谢.
推荐答案
而不是将Object强制转换为JSONArray,您应该这样做:
Instead of casting your Object to JSONArray, you should do it like this:
JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
mJsonObject.getString("0");
mJsonObject.getString("id");
mJsonObject.getString("1");
mJsonObject.getString("name");
}
这篇关于使用Java解码对象的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文