【问题标题】:Android parse json force stoppedAndroid解析json强制停止
【发布时间】:2016-03-25 20:40:58
【问题描述】:

我正在解析一个 json url:http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2,但我没能做到。我收到一个错误。这段代码有什么问题?

public void parseJsonResponse(String result) {
    Log.i(TAG, result);
    pageCount++;
    try {
        JSONObject json = new JSONObject(result);
        JSONArray jArray = json.getJSONArray("name");
        for (int i = 0; i < jArray.length(); i++) {

            JSONObject jObject = jArray.getJSONObject(i);
            CountryInfor country = new CountryInfor();
            country.setId(jObject.getString("id"));
            country.setName(jObject.getString("name"));
            countries.add(country);
        }

        adapter.notifyDataSetChanged();
        if (dialog != null) {
            dialog.dismiss();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 堆栈跟踪在哪里?

标签: android json


【解决方案1】:

替换

JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");

这两行

JSONArray jArray = new JSONArray(result);

也改变

country.setId(jObject.getString("id"));

通过

country.setId(jObject.getInt("id") + "");

因为id 的类型是int 而不是String

它会正常工作的。

你得到了类似的回应

[
    {
        "id": ​1,
        "name": "Vietnam"
    },
    {
        "id": ​2,
        "name": "China"
    },
    {
        "id": ​3,
        "name": "USA"
    },
    {
        "id": ​4,
        "name": "England"
    },
    {
        "id": ​10,
        "name": "Russia"
    }
]

所以响应是JSONArray 而不是JSONObject

希望对你有所帮助。

编辑

@Override
protected String doInBackground(Void... params) {

    // call load JSON from url method
    if(loadJSON(this.url) != null) {
        return loadJSON(this.url).toString();
    }
    Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
    return null;
}

你得到JSONObject null,所以错误是。

- 你应该知道what is NullPointerException

【讨论】:

  • 我收到此错误:解析数据时出错 org.json.JSONException:Java.lang.Integer 类型的值 404 无法转换为 JSONObject
  • 粘贴整个 logcat,以便我可以获取有关错误的更多信息。
  • 您在LoadCountriesFromUrlTask.java:53 获得了java.lang.NullPointerException,这在here 进行了解释
  • 检查答案并尝试从链接中提供的答案中学习。
【解决方案2】:

问题在于这一行

JSONArray jArray = json.getJSONArray("name");

没有名称为name 的数组。它在这里失败了。更正此部分以正确获取数组。休息看起来不错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多