JaskeyLam
JaskeyLam

Reputation: 15755

Convert xml string to JSON string without using third party libs

I have some string in xml format and need to convert it into JSON format. I have read Quickest way to convert XML to JSON in Java but we can't use any external libs but standard Java.

Is there any simple or good way to achieve this without any third party libs?

Here is the xml string looks like:

<container>
     <someString>xxx</someString>     
     <someInteger>123</someInteger>     
     <someArrayElem>         
        <key>1111</key>         
        <value>One</value>     
    </someArrayElem>     

    <someArrayElem>         
    <key>2222</key>         
    <value>Two</value>     
    </someArrayElem> 
</container>

Need change it into:

{

   "someString": "xxx",   
   "someInteger": "123",
   "someArrayElem": [
      {
         "key": "1111",
         "value": "One"
      },

      {
         "key": "2222",
         "value": "Two"
      }
   ]

}

Upvotes: 0

Views: 6562

Answers (1)

bvdb
bvdb

Reputation: 24750

You could look at this problem, from the point of view of XSL transformations. So, you could use JAXP, which is included in the Java SE SDK (no additional dependencies).

  // raw xml
  String rawXml= ... ;

  // raw Xsl
  String rawXslt= ... ;

  // create a transformer
  Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(
     new StreamSource(new StringReader(rawXslt))
  );

  // perform transformation
  StringWriter result = new StringWriter();
  xmlTransformer.transform(
     new StreamSource(new StringReader(rawXml)), new StreamResult(result)
  );

  // print output
  System.out.println(result.getBuffer().toString());

You already have your XML, all what you need now, is your XSL code. I was about to write you one from scratch, when I found out that this website already did it for me/you. Here's a direct link to the XSL file that they made.

Note: this is a one-way conversion. You cannot use it to convert JSON back to XML.

Enjoy.

Upvotes: 2

Related Questions