Ajith
Ajith

Reputation: 97

Convert xml with namespaces to json in java

I'm trying to convert xml to json using java and then convert the json back to xml after modifying which should give the same xml. The xml attributes have namespaces.

My sample xml :

<?xml version="1.0" encoding="UTF-8"?>
<ns2:testplan xmlns:ns2="http://jazz.net/xmlns/alm/qm/v0.1/" xmlns:ns1="http://schema.ibm.com/vega/2008/" xmlns:ns3="http://purl.org/dc/elements/1.1/" xmlns:ns4="http://jazz.net/xmlns/prod/jazz/process/0.6/" xmlns:ns5="http://jazz.net/xmlns/alm/v0.1/" xmlns:ns6="http://purl.org/dc/terms/" xmlns:ns7="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:ns8="http://jazz.net/xmlns/alm/qm/v0.1/testscript/v0.1/" xmlns:ns9="http://jazz.net/xmlns/alm/qm/v0.1/executionworkitem/v0.1" xmlns:ns10="http://open-services.net/ns/core#" xmlns:ns11="http://open-services.net/ns/qm#" xmlns:ns12="http://jazz.net/xmlns/prod/jazz/rqm/process/1.0/" xmlns:ns13="http://www.w3.org/2002/07/owl#" xmlns:ns14="http://jazz.net/xmlns/alm/qm/qmadapter/v0.1" xmlns:ns15="http://jazz.net/xmlns/alm/qm/qmadapter/task/v0.1" xmlns:ns16="http://jazz.net/xmlns/alm/qm/v0.1/executionresult/v0.1" xmlns:ns17="http://jazz.net/xmlns/alm/qm/v0.1/catalog/v0.1" xmlns:ns18="http://jazz.net/xmlns/alm/qm/v0.1/tsl/v0.1/" xmlns:ns20="http://jazz.net/xmlns/alm/qm/styleinfo/v0.1/" xmlns:ns21="http://www.w3.org/1999/XSL/Transform">
<ns2:projectArea href="https://testserver:9080/qm/resource/itemOid/com.ibm.team.process.ProjectArea/_xv6jsJceEeimRT_G_Q" alias="projectArea"/>
<ns3:identifier>https://testserver:9080/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/projectArea/testplan/urn:com.ibm.rqm:testplan:70?revision=294</ns3:identifier>
<ns2:stylesheet href="https://testserver:9080/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/projectArea/testplan/urn:com.ibm.rqm:testplan:70?stylesheet=true"/>
<ns2:snapshot>
<ns3:title>testplan_70_&lt;Reason&gt;_&lt;Version&gt;_on_16 Apr 2019 05:50</ns3:title>
<ns5:updated>2019-04-16T12:20:01.644Z</ns5:updated>
<ns2:revision>294</ns2:revision>
</ns2:snapshot>
<ns2:webId>70</ns2:webId>
<ns3:title>Demo test plan 06</ns3:title>
<ns3:description/>
<ns2:creationDate>2019-01-22T10:36:40.289Z</ns2:creationDate>
<ns5:updated>2019-04-16T12:20:01.644Z</ns5:updated>
<ns5:state ns7:resource="https://testserver:9080/qm/service/com.ibm.rqm.integration.service.IIntegrationService/process-info/_xv6jsJceEeRT_G_Q/workflowstate/com.ibm.rqm.process.testplan.workflow/com.ibm.rqm.planning.common.underreview">com.ibm.rqm.planning.common.underreview</ns5:state>
<ns3:creator ns7:resource="https://testserver:9080/jts/resource/itemName/com.ibm.team.repository.Contributor/ABB">abc</ns3:creator>
<ns5:owner>unassigned</ns5:owner>
<ns2:priority ns7:resource="https://testserver:9080/qm/service/com.ibm.rqm.integration.service.IIntegrationService/process-info/_xv6jsJceEeimbPqQ/priority/literal.priority.101">literal.priority.101</ns2:priority>
<ns2:locked>false</ns2:locked>
<ns2:component href="https://testserver:9080/qm/service/com.ibm.rqm.integration.service.IIntegrationService/resources/projectArea/component/_yzQ3EZcmbPqnRT_G_Q"/>
</ns2:testplan>
 

Could someone please help me to convert preciously using java.

I have tried converting using org.json.XML, But it was not giving proper json with jsonobject keys/values having namespaces.

Code I have tried and not giving response:

JSONObject jsonObject = XML.toJSONObject("xml");
 

I expect a convertion way which gives Json with proper format and json objects having namespaces,and If I covert this json it should give initial xml Please help me.

Upvotes: 1

Views: 5072

Answers (3)

akuma8
akuma8

Reputation: 4691

This question is a bit old but I would like to share my answer about the same task that I did recently! The requirement is: Having this xml:

<ns2:testplan>
 <ns2:snapshot>
    <ns2:revision>294</ns2:revision>
 </ns2:snapshot>
 <ns2:webId>70</ns2:webId>
 <ns2:title>Demo test plan 06</ns2:title>
</ns2:testplan>

We would like to convert it to:

{
  "ns2:testplan": {
    "ns2:snapshot": {
      "ns2:revision": 294
    },
    "ns2:title": "Demo test plan 06",
    "ns2:webId": 70
  }
}

Note that with the accepted response the root tag <ns2:testplan> and the namespace prefix are not included in the JSON. To configure XmlMapper to keep the namespace and add the root tag, proceed like this:

var module = new SimpleModule().addDeserializer(JsonNode.class, new JsonNodeDeserializer() {
        @Override
        public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return ctxt.getNodeFactory()
                    .objectNode()
                    .set("ns2:testplan", super.deserialize(p, ctxt)); // this config adds the root tag
        }
    });

XMLInputFactory xmlInputFactory = new WstxInputFactory();
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); // this one keeps the namespace prefix
XmlMapper xmlMapper = new XmlMapper(new XmlFactory(xmlInputFactory, new WstxOutputFactory()));
xmlMapper.registerModule(module);

Then use the code of the accepted answer to convert the XML to JSON.

Upvotes: 1

tobsob
tobsob

Reputation: 602

You could try the XmlMapper from jackson (com.fasterxml.jackson.dataformat.xml.XmlMapper)

XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonNode = xmlMapper.readTree(string.getBytes());
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(jsonNode);

edit: Dependencies I've used

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
</dependency>
<dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.9.0</version>
</dependency>

Upvotes: 1

Genhis
Genhis

Reputation: 1524

Get a JSONObject and convert it to JSON string:

JSONObject jsonObject = XML.toJSONObject("xml");
String jsonString = jsonObject.toString();

If you want to pretty-print the string, use toString(int) which takes number of spaces as an argument.

String prettyPrintedJson = jsonObject.toString(4);

Upvotes: -1

Related Questions