一尘不染

解析ANDROID中的嵌套JSON

json

我正在尝试解析这种结构:(它使我发疯,并且我尝试了我能想到的一切。但是我不是很有经验)

{
    "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个播放器JSONObject。但是在JSON术语中,最重要的是什么。我在JSON验证程序上签出有效的凭证,我需要这样的凭证:

topDrop作为JSONObject Player,作为JSONArray,并循环遍历数组中的对象。

有什么建议?/约翰


阅读 242

收藏
2020-07-27

共1个答案

一尘不染

这是我从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);
}
}
2020-07-27