将SOAP响应转换为JSONArray

我有SOAP响应如下。 我想迭代soap消息,并希望以JSONArray格式获取listMetadataResponse标记中的数据。 这是我的SOAP响应示例:

     00528000001m5RRAAY Hariprasath Thanarajah 1970-01-01T00:00:00.000Z objects/EmailMessage.object EmailMessage  00528000001m5RRAAY Hariprasath Thanarajah 1970-01-01T00:00:00.000Z  CustomObject   00528000001m5RRAAY Hariprasath Thanarajah 1970-01-01T00:00:00.000Z objects/EmailMessage.object EmailMessage  00528000001m5RRAAY Hariprasath Thanarajah 1970-01-01T00:00:00.000Z  CustomObject     

我希望将每个结果节点作为JSONObject与每个属性节点和值作为JSON中的键值对进行。在这种情况下,我希望结果为JSONArray,其中包含两个结果JSONObject。

我试过这段代码。 我正在获取节点名称,但我没有得到节点值。

 private static Document loadXMLString(String response) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(response)); return db.parse(is); } public static JSONArray getFullData(String tagName, String request) throws Exception { JSONArray resultArray = new JSONArray(); Document xmlDoc = loadXMLString(request); NodeList nodeList = xmlDoc.getElementsByTagName("*"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("result")) { JSONObject rootObject = new JSONObject(); NodeList childNodeList = nodeList.item(i).getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { node = childNodeList.item(i); rootObject.put(node.getNodeName(), node.getNodeValue()); } resultArray.put(rootObject); } } } } 

您可以通过stleary使用JSON-java库。

您可以使用以下代码将XML字符串转换为JSONObject。

JSONObject data = XML.toJSONObject(xmlString);

你可以在这里找到更多关于它的信息: JSON-java

通过上面的参考,我至少可以实现解决方案。我希望这对其他人也有用。

 private static JSONObject extractData(NodeList nodeList, String tagName) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError, JSONException { JSONObject resultObject = new JSONObject(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (!node.getNodeName().equals(tagName) && node.hasChildNodes()) { return extractData(node.getChildNodes(), tagName); } else if (node.getNodeName().equals(tagName)) { DOMSource source = new DOMSource(node); StringWriter stringResult = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult)); resultObject = XML.toJSONObject(stringResult.toString()).optJSONObject(tagName); } } return resultObject; } public static JSONObject getFullData(String tagName, SOAPMessage message) throws Exception { NodeList nodeList = message.getSOAPBody().getChildNodes(); JSONObject resultObject = extractData(nodeList, tagName); return resultObject; }