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

}
3
  • 3
    Is there any simple or good way to do this? Using third party libraries, yes. All other ways are bad and not simple. Commented Dec 1, 2014 at 6: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? Commented Dec 1, 2014 at 6: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. Commented Dec 1, 2014 at 6:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.