Android:解析JSON文件问题

时间:2013-07-19 13:48:41

标签: android arrays json parsing

我在我的应用程序中一直在与一些JSON解析进行斗争,经过3天的研究,我仍然无法弄清楚问题。

正在发送的错误是“org.json.JSONException:Value”

我在一个我一直在努力的try / catch语句中得到了错误。

我的Try / Catch看起来像这样:

Try {
    // Result comes in from an HTTP Request

    JSONArray jarray = new JSONArray(result);
    JSONObject jObj = jarray.getJSONObject(0).getJSONObject("results");
    String TeamName = jObj.getString("fulltext");
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

我收到的完整JSON位于here,但删节版本如下:

{
    "query-continue-offset": 50,
    "query": {
        "printrequests": [{
            "label": "",
            "typeid": "_wpg",
            "mode": 2,
            "format": false
        }],
        "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
            },
            "Team:(OHC) Kubb Team": {
                "printouts": [],
                "fulltext": "Team:(OHC) Kubb Team",
                "fullurl": "http:\/\/wiki.planetkubb.com\/wiki\/Team:(OHC)_Kubb_Team",
                "namespace": 822,
                "exists": true
            },
            "Team:Andrewsons3": {
                "printouts": [],
                "fulltext": "Team:Andrewsons3",
                "fullurl": "http:\/\/wiki.planetkubb.com\/wiki\/Team:Andrewsons3",
                "namespace": 822,
                "exists": true
            }
        },
        "meta": {
            "hash": "46923025c2d5aac3ee963419db93485d",
            "count": 50,
            "offset": 0
        }
    }
}

这是我第一次看到JSON代码,说实话,起初有点令人困惑,但我可以理解JSON是如何工作的,而不是如何从这些数组中获取数据!

我错过了一些东西,我只是看不到...

1 个答案:

答案 0 :(得分:0)

您获得的错误来自以下一行:

String TeamName = jObj.getString("fulltext");

这是因为值jObj没有“全文”值。相反,该字段是每个子JSONObject的值。要避免此错误,您首先需要检查JSONObject是否具有变量“fulltext”:

String TeamName = null;
if (jObj.has("fulltext"))
    TeamName = jObj.getString("fulltext");

为了简化您的JSON解析,droidQuery提供了一些从MapJSONObject s创建JSONArray和数组的简单方法:

Map<String, ?> map = $.map(jObj);
for (Entry<String, ?> entry : map.entrySet()) {
    String teamName = entry.key();
    JSONObject json = (JSONObject) entry.value();
    Map<String, ?> team = $.map(json);
    String fulltext = (String) team.get("fulltext");//etc
}