【问题标题】:Extracting text from Http response从 Http 响应中提取文本
【发布时间】:2018-05-01 17:01:05
【问题描述】:

下面是java中http响应的截图——

以下是响应的文本形式:

{
  "LightGingerTheTextResult": [
    {
      "Confidence": 4,
      "From": 0,
      "LrnFrg": null,
      "LrnFrgOrigIndxs": [],
      "Mistakes": [
        {
          "CanAddToDict": false,
          "From": 0,
          "To": 0
        }
      ],
      "ShouldReplace": true,
      "Suggestions": [
        {
          "LrnCatId": 12,
          "Text": "An"
        },
        {
          "LrnCatId": 45,
          "Text": "A"
        }
      ],
      "To": 0,
      "TopLrnCatId": 12,
      "Type": 3,
      "UXFrgFrom": 0,
      "UXFrgTo": 6
    }
  ]
}

我想提取建议中的“文本”。

这是我对 json 的一部分。我在“finalResult”中得到最终回复-

JSONObject json = new JSONObject();
        try
        {
            StringBuffer response =urllib.urlopen(url);
            String finalResponse= response.toString();
            System.out.println("final response"+finalResponse);
            StringBuffer result=(StringBuffer) json.get(finalResponse);
            //finalResult=URLEncoder.encode(result.toString(), "UTF-8");
            String finalResult=result.toString();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }

【问题讨论】:

  • 使用一些对象映射将 json 映射到 POJO,然后简单地访问它的 text 属性。
  • 或者使用像JSON-P这样的JSON解析器。
  • 向我们展示您尝试解决此问题的方法。它有效吗?如果没有,什么不起作用?
  • 响应是 JSON 文本(正如你所知道的,因为你已经标记了它),所以使用 JSON 库来处理它。
  • 接受响应作​​为字符串并使用 jsonpath 库。看到这个stackoverflow.com/a/34117168/3295987。但是最好将 json 与 POJO 映射,因为您可能还需要其他字段(如果不是现在,那么将来)

标签: java json httpresponse


【解决方案1】:

stackoverflow.com/questions/2591098。你需要一个图书馆, 使用包org.json

new JSONObject(textOfResponse)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(0)
.getString("Text")

你的textOfResponse 我明白了

An

【讨论】:

  • 它返回 'Null Key' 作为响应
  • 奇怪,补充一些细节
  • @first 使用 JSONObject 如果你调用 .getJSONArray(null).getString(null) 你会得到一个 Exception in thread "..." org.json.JSONException: Null key.
【解决方案2】:

如果您正在寻找特定 JSON 节点的值,您可以使用 JsonPath expression 例如提取所有 Text 节点的值:

$.LightGingerTheTextResult[*].Suggestions[*].Text

在您的示例中简化为

$..Text

或者只是来自第一个Suggestions 节点的第一个Text 节点:

$.LightGingerTheTextResult[0].Suggestions[0].Text

【讨论】:

  • 你能给我举个例子吗?我在网上搜索过,但我不明白。
  • 添加此代码后,我得到“json 不能为空或为空”作为响应
【解决方案3】:

我建议您首先检索您的 httpResponse 对象的主体。

 String tmp = response.body();   // I assume the callback method has a an 
                                 //argument of type 
                                 //httpResponse called response

然后将其存储在某个地方,例如:字符串。

使用 gson 并使用 httpResponse 类

像这样: httpResponse rep = gson.fromJson(, httpResponse .class); 这样,您现在可以使用 rep 对象来检索您想要的任何内容。

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2019-02-09
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多