我正在尝试解析这个结构:(它让我发疯,我尝试了我能想到的一切。但是我不是很有经验)
{
"topDrops" : {
"week" : "14",
"player" : [ {
"percent" : "3.70",
"id" : "10948"
}, {
"percent" : "3.49",
"id" : "0532"
}, {
"percent" : "2.46",
"id" : "11214"
}, {
"percent" : "2.20",
"id" : "0529"
}, {
"percent" : "2.04",
"id" : "0508"
} ]
},
"version" : "1.0",
"encoding" : "ISO-8859-1"
}
“topDrop”就像一个文件名? player 是一个 JSONArray,由 5 个播放器 JSONObjects 组成。但是在 JSON 术语中什么是顶级。我在 JSON 验证器上检查了 valid 我需要类似的东西:
topDrop 作为 JSONObject
播放器作为 JSONArray
并循环遍历数组中的对象。
有什么建议吗?
/约翰
这是我从 URL 解析 json 的代码:
public JSONObject getJSONFromUrl(String url) {
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
json = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jObj;
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.v("debug", "JSON ready to parsing");
return jObj;
}
public void parsingData(JSONObject json) {
try {
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
// Do your stuff, example :
JSONObject c = data.getJSONObject(i);
JSONObject topDrops = c.getJSONObject("topDrops");
JSONArray playerArray = topDrops.getJSONArray("player");
// playerArray.getJSONObject(0) == first player
}
} catch (JSONException e) {
e.printStackTrace();
Log.v("debug", "Error during the connection HTTP");
cancel(Boolean.TRUE);
}
}