0

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"
      }
   ]

}
Community
  • 1
  • 1
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
  • 3
    _Is there any simple or good way to do this?_ Using third party libraries, yes. All other ways are bad and not simple. – Sotirios Delimanolis Dec 01 '14 at 06:44
  • @SotiriosDelimanolis , well, we just can't use any libs. my format is simple xml without attribute or something fancy, Is there any apis using standard java to convert? – JaskeyLam Dec 01 '14 at 06:47
  • Nope. Note also that there isn't a standard 1-to-1 mapping between XML elements and JSON members. You have to define the conversion. – Sotirios Delimanolis Dec 01 '14 at 06:48

1 Answers1

2

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.

bvdb
  • 22,839
  • 10
  • 110
  • 123