【问题标题】:Find specific JSON object in JSONArray from HttpResponse从 HttpResponse 中查找 JSONArray 中的特定 JSON 对象
【发布时间】:2015-08-27 08:55:06
【问题描述】:

这是我的代码现在的样子:

HttpResponse response = client.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
int statuscode = response.getStatusLine().getStatusCode();
System.out.println(responseBody);

我得到的响应如下所示:

{"developerMessage":"The requested resource is not available.",
"httpStatusCode":"404",
"errors":[{"developerMessage":"Savings account with identifier 15 does not exist"

我想要得到的是“标识符为 15 的储蓄账户不存在”作为字符串。

有什么想法吗?

【问题讨论】:

    标签: json rest httpclient response


    【解决方案1】:

    试试这个

            String jsonString = "{\n" +
                    "    \"developerMessage\": \"The requested resource is not available.\",\n" +
                    "    \"httpStatusCode\": \"404\",\n" +
                    "    \"errors\": [\n" +
                    "        {\n" +
                    "            \"developerMessage\": \"Savings account with identifier 15 does not exist\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
    
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String string = jsonObject.getString("errors");
                JSONArray jsonArray = new JSONArray(string);
                JSONObject jsonObject2 = jsonArray.getJSONObject(0);
                String message = jsonObject2.getString("developerMessage");
                Log.i("YourApp", message);
            } catch (JSONException e) {
                e.printStackTrace();
            }
    

    【讨论】:

    • 我收到以下错误:org.json.JSONException: JSONObject["errors"] not a string.
    • 我的代码在发布之前测试正常。我认为您应该检查您的响应消息是否是有效的 Json。您可以在 jsonlint.com 上查看。看我的jsonString,和你的不一样吗?
    • 您发布的 jsonString 是我在 println(responseBody) 时在 java 中得到的输出,我从 String responseBody = EntityUtils.toString(response.getEntity());
    • 我不希望对错误进行硬编码,我希望将错误作为响应,并能够使用错误字符串将其插入到我的数据库中
    • 谢谢,有点晚了,但有了更多的知识,我更好地理解了你的答案,现在它就像一个魅力
    猜你喜欢
    • 2018-03-24
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    相关资源
    最近更新 更多