Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To convert SOAP response to JSONArray

Tags:

java

json

soap

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:

 <?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.

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);
            }
        }
    }
}
like image 410
Chetan chadha Avatar asked Sep 19 '25 00:09

Chetan chadha


2 Answers

You can use JSON-java library by stleary.

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

JSONObject data = XML.toJSONObject(xmlString);

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

like image 143
Chinmay jain Avatar answered Sep 21 '25 13:09

Chinmay jain


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;
}
like image 29
Chetan chadha Avatar answered Sep 21 '25 15:09

Chetan chadha