Search code examples
javajsonxmlspring-boot

Convert XML to JSON and Vice Versa and also how to identify REST endpoint while making XML Request?


My company has exposed REST endpoint to external world through Proxy/Gateway. Around 1000 of customers are on-boarded to Proxy/Gateway and making XML request to SOAP based system (deployed on WebSphere App Server (WAS) V7.5).

Now, we've developed new system which only supports JSON and wanted to point to newly developed system which deployed on PCF (Pivotal Cloud Foundry).

Here we don't want to ask Consumers to make any changes.

Now, we're trying to developed Adapter (Spring Boot Project) which converts XML request to JSON make a request to new system and get response in JSON and again Adapter (Spring Boot Project) converts JSON to XML. Here, JSON response and XML response could be different at times.

Now, I am really not able to make any decision which endpoint to call to

String xml_data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:ahc.com:dms:wsdls:organization\">\n" + 
        "   <soapenv:Header/>\n" + 
        "   <soapenv:Body>\n" + 
        "      <urn:getRoles>\n" + 
        "         <getRolesRequest>\n" + 
        "            <Type>ABC</Type>\n" + 
        "         </getRolesRequest>\n" + 
        "      </urn:getRoles>\n" + 
        "   </soapenv:Body>\n" + 
        "</soapenv:Envelope>";
JSONObject obj = XML.toJSONObject(xml_data);
System.out.println(obj);

It gives me below response.

{"soapenv:Envelope":{"soapenv:Body":{"urn:getRoles":{"getRolesRequest":{"Type":"AYU"}}},"xmlns:soapenv":"http://schemas.xmlsoap.org/soap/envelope/","xmlns:urn":"urn:ahc.com:dms:wsdls:organization","soapenv:Header":""}}

Any guidance ?

Note: I want to remove <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\ from JSON object. Also, while convering JSON to XML I want to add <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\


Solution

  • You may use the underscore-java library. It has static methods to read xml and generate json.

        String xmlData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""
        + " xmlns:urn=\"urn:ahc.com:dms:wsdls:organization\">\n"
        + "   <soapenv:Header/>\n"
        + "   <soapenv:Body>\n"
        + "      <urn:getRoles>\n"
        + "         <getRolesRequest>\n"
        + "            <Type>ABC</Type>\n"
        + "         </getRolesRequest>\n"
        + "      </urn:getRoles>\n"
        + "   </soapenv:Body>\n"
        + "</soapenv:Envelope>";
        Map<String, Object> jsonData = U.<Map<String, Object>>get(
            U.<Map<String, Object>>fromXmlWithoutNamespaces(xmlData), "Envelope.Body.getRoles");
        System.out.println(U.toJson(jsonData));
    

    Output:

    {
      "getRolesRequest": {
        "Type": "ABC"
      }
    }