JSON 解析问题 Redux

JSON parsing Issues Redux

我过去在解析我的 JSON 代码时遇到过问题,我几乎遇到了问题并且丢失了所有代码更改。我把它的胆量放在这里得到我的JSON(我已经证实它没问题)。只是对其进行解析...我需要获取 "fulltext" 字段,我想将其放入数组中...

try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");
            result = sb.toString();


        } catch (Exception e) {
            Log.e("log_tag" , "Error converting result " + e.toString());
        }

        try{

            JSONObject rootobject = new JSONObject(result).getJSONObject("query").getJSONObject("results");


        } catch (JSONException e){
            Log.e("JSON Parser", Log.getStackTraceString(e));
            e.printStackTrace();
        }



        return null;

其中,JSON对象区域我认为是不正确的。我需要遍历所有 JSON 对象,从它们中获取 "fulltext" 值,并最终将它们放入数据库。我正在从这个网站上提取团队名称。

在我看来,我应该可以使用

String teamname = rootobject.getString("fulltext");

在某种程度上。我试过这个,但它根本不起作用。事实上,当我检查错误日志时,我收到了错误消息 "No value for fulltext"。

我知道我在某处出错了,但不能完全正确。我仍然对 JSON 解析和诸如此类的东西感到困惑,但我决心做到这一点。

这是示例 JSON(我正在访问的 URL)的 link

http://bit.ly/1JnlSck

很抱歉在第一个 post 中忘记了这一点。

您可能应该做的是重组您的 JSON。目前你有这样的...

"results": {
    "Team:\"Die Unglaublichen\"": {
        "printouts": [],
        "fulltext": "Team:\"Die Unglaublichen\"",
        "fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
        "namespace": 822,
        "exists": true
    },
    "Team:(Can't Stand) Le Kubb Bricks": {
        "printouts": [],
        "fulltext": "Team:(Can't Stand) Le Kubb Bricks",
        "fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
        "namespace": 822,
        "exists": true
    }
}

... 其中 "results" 是一个包含多个子 JSON 对象的 JSON 对象。如果你可以修改它,使 "results" 是一个包含 JSON 对象的 JSON 数组,就像这样...

"results": [
    {
        "Team": "Die Unglaublichen",
        "printouts": [],
        "fulltext": "Team:\"Die Unglaublichen\"",
        "fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
        "namespace": 822,
        "exists": true
    },
    {
        "Team": "(Can't Stand) Le Kubb Bricks",
        "printouts": [],
        "fulltext": "Team:(Can't Stand) Le Kubb Bricks",
        "fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
        "namespace": 822,
        "exists": true
    }
]

... 然后你可以遍历 "results" 数组并获取它的每个 JSON 对象和你想要的任何 name/values:

try {
    JSONArray resultsArray = rootObject.getJSONArray("results");
    for (int i = 0; i < resultsArray.length(); i++) {
        JSONObject teamObject = resultsArray.getJSONObject(i);
        String fullText = teamObject.getString("fulltext");
    }
} catch (JSONException e) {
    e.printStackTrace();
}