从 java 中的 watson 对话服务解析 JSON

Parse JSON from conversation service of watson in java

我正在使用 watson 服务并尝试为我的应用程序构建一个聊天框,来自 watson API 的响应采用 JSON 的形式,如下所示:

   {
  "context": {
    "conversation_id": "00d5c35d-ab4e-47d3-a7fd-2b78d57df59f",
    "system": {
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1.0,
      "dialog_request_counter": 1.0,
      "_node_output_map": {
        "node_4_1487236585212": [
          0.0
        ]
      },
      "dialog_in_progress": false
    }
  },
  "entities": [],
  "intents": [
    {
      "confidence": 1.0,
      "intent": "Hello"
    },
    {
      "confidence": 0.0,
      "intent": "GoodBye"
    }
  ],
  "output": {
    "log_messages": [],
    "text": [
      "Welcome to my conversation app"
    ],
    "nodes_visited": [
      "node1"
    ]
  },
  "input": {
    "text": "hii"
  }
}

现在在我的应用程序中,我需要从 JSON 响应中获取 "output" 键的数据,并从 "output" 键中获取 "text" 键的数据。

我正在尝试做的事情如下:

MessageRequest options = new MessageRequest.Builder().inputText(message).alternateIntents(true).context(context).build();



        MessageResponse response = service.message("93576d15-15a9-4029-bc07-41da7f2efa39", options).execute();


        context = response.getContext();

        /*System.out.println(context);*/

        System.out.println(response);

        try {
            JSONObject contObj = new JSONObject(response);

            System.out.println(contObj.getString("output"));


            JSONObject contObj1 = new JSONObject(contObj);
            System.out.println(contObj1);
            System.out.println("TEXT OUTPUT"+contObj1.getString("text"));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

现在包含 "output" 的系统输出给出了正确的值,但是包含 "text" 的系统输出给出了空值。 任何帮助将不胜感激。谢谢

文本”不是字符串。它是一个数组。这就是 contObj.getString("text") 不起作用的原因。

我不知道 Java 的语法,但在 Java 脚本中你可以像 output.text[0] 一样访问它,所以你应该在你的代码中做同样的事情。

嗨,在各种网站上搜索相同的东西遇到了很多麻烦,但没有得到任何帮助,我尝试使用 eclipse 的 ctrl+space 选项,最终得到了同样的解决方案。以后可能遇到此类问题的小伙伴可以参考下面的代码。

JSONObject contObj = new JSONObject(res);

            outputText = (contObj.getJSONObject("output").getJSONArray("text").get(0).toString());
            System.out.println("outputText: "+outputText);

这就是我为获得所需输出所做的工作。并感谢所有尝试在这个问题上帮助我的人。