android - 在 ANDROID 中解析嵌套的 JSON

标签 android json parsing

<分区>

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

{
    "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);
}
}

关于android - 在 ANDROID 中解析嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289899/

相关文章:

适用于小屏幕的 Android eclipse 图片

android - 将无接触手势整合到我的Android应用程序中

android - 将 Map<String, String> 保存到房间数据库的方法

java - 如何在 Java 中使用 JSONObject 设置整数值?

java - 将数据文件转换为 JUnit 的 Java 静态类常量

java - 如何在 Lucene QueryParser 中指定两个字段?

java - Android - 保存到文本文件

json - 如何在 R 中使用管道工 api 返回 JSON

c# 将带有对象列表的 json 字符串转换为 c# 对象

c++ - 无法解析句子时使用 Silent Charniak Parse - 它不起作用