如何让IBM Natural Language Understanding返回XML格式输出?
IBM NLU JSON转XML解决方案
首先明确说:IBM Natural Language Understanding(NLU)原生不支持直接返回XML格式的响应,这就是你添加Accept: application/xml头后收到406错误的原因——服务器无法提供你请求的媒体类型。
为什么会这样?
虽然Watson系列的部分老服务(比如你提到的Watson Explorer)依赖XML,但NLU是基于现代REST API设计的,它的响应输出仅支持JSON格式,官方文档里也没有提及XML输出的支持。
可行的解决办法
既然无法让NLU直接返回XML,你可以在收到JSON响应后,自己做格式转换,这里给你几个常见语言的实现思路:
Python:使用
xmltodict库,先解析NLU返回的JSON,再转为XML:import json import xmltodict # 假设nlu_response是你收到的JSON响应字符串 nlu_json = json.loads(nlu_response) xml_output = xmltodict.unparse(nlu_json, pretty=True) print(xml_output)JavaScript:使用
json2xml包,在Node.js环境中处理:const json2xml = require('json2xml'); const nluJson = /* 你的NLU JSON响应对象 */; const xmlOutput = json2xml(nluJson, { prettyPrint: true }); console.log(xmlOutput);Java:使用Jackson库同时处理JSON和XML转换:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; // 解析JSON响应 ObjectMapper jsonMapper = new ObjectMapper(); JsonNode nluJson = jsonMapper.readTree(nluResponseString); // 转换为XML XmlMapper xmlMapper = new XmlMapper(); String xmlOutput = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(nluJson); System.out.println(xmlOutput);
这些工具都能帮你快速完成JSON到XML的转换,适配你的需求。
内容的提问来源于stack exchange,提问作者Joost Vos
相关产品推荐
相关产品推荐

