java 将 SOAP 响应转换为 JSONArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45366111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:39:43  来源:igfitidea点击:

To convert SOAP response to JSONArray

javajsonsoap

提问by Chetan chadha

I have the SOAP response as below. I want to iterate over the soap message and want to get the data in the listMetadataResponse tag in JSONArray format. Here is my sample SOAP response:

我有如下 SOAP 响应。我想遍历soap消息并想以JSONArray格式获取listMetadataResponse标签中的数据。这是我的示例 SOAP 响应:

 <?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata">
       <soapenv:Body>
          <listMetadataResponse>
             <result>
                <createdById>00528000001m5RRAAY</createdById>
                <createdByName>Hariprasath Thanarajah</createdByName>
                <createdDate>1970-01-01T00:00:00.000Z</createdDate>
                <fileName>objects/EmailMessage.object</fileName>
                <fullName>EmailMessage</fullName>
                <id />
                <lastModifiedById>00528000001m5RRAAY</lastModifiedById>
                <lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
                <lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
                <namespacePrefix />
                <type>CustomObject</type>
             </result>
              <result>
                <createdById>00528000001m5RRAAY</createdById>
                <createdByName>Hariprasath Thanarajah</createdByName>
                <createdDate>1970-01-01T00:00:00.000Z</createdDate>
                <fileName>objects/EmailMessage.object</fileName>
                <fullName>EmailMessage</fullName>
                <id />
                <lastModifiedById>00528000001m5RRAAY</lastModifiedById>
                <lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
                <lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
                <namespacePrefix />
                <type>CustomObject</type>
             </result>
          </listMetadataResponse>
       </soapenv:Body>
    </soapenv:Envelope>

I want to get each of the result nodes as JSONObject with each attribute node and values as key value pair in JSON.So, in this case, I want the result as a JSONArray with two results JSONObject in it.

我想将每个结果节点作为 JSONObject 获取,每个属性节点和值作为 JSON 中的键值对。所以,在这种情况下,我希望结果作为一个 JSONArray,其中包含两个结果 JSONObject。

I have tried this code. I am getting node names but I am not getting the node values.

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

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);
            }
        }
    }
}

采纳答案by Chinmay jain

You can use JSON-java library by stleary.

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

You can use the following code to convert an XML string into JSONObject.

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

JSONObject data = XML.toJSONObject(xmlString);

JSONObject data = XML.toJSONObject(xmlString);

You can find more info about it here: JSON-java

您可以在此处找到有关它的更多信息:JSON-java

回答by Chetan chadha

With the above reference, I am able to implement the solution at least.I hope this will work for others as well.

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

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;
}