Xml to Json to xml reversible conversion json-lib

1.1k views Asked by At

I am trying to do reversible xml-json-xml generic conversion using json-lib which according to its documentation does the conversion as described in Converting Between Xml And Json. According to the document:

A structured XML element can be converted to a reversible JSON structure, if

  • all subelement names occur exactly once, or
  • subelements with identical names are in sequence.

I tried the following code snippet:

String xml ="<z><y>dfsdfs</y><y>sdf</y><x>afdf</x></z>";
System.out.println("Original Xml: " + xml);
XMLSerializer xmlSerializer = new XMLSerializer(); 
xmlSerializer.setForceTopLevelObject(true);
xmlSerializer.setTypeHintsEnabled(false);
JSON json = xmlSerializer.read( xml );  
String jsonString = json.toString(2);   
System.out.println("Converted Json: " + jsonString);
JSON json2 = JSONSerializer.toJSON( jsonString );  
String xml2 = xmlSerializer.write( json2 );  
System.out.println("Converted Xml:" + xml2);  

Notice the sample xml does follow the conditions. However, the result is:

Original Xml: <z><y>dfsdfs</y><y>sdf</y><x>afdf</x></z>

Converted Json: {"z": {
  "y":   [
    "dfsdfs",
    "sdf"
  ],
  "x": "afdf"
}}

Converted Xml:<?xml version="1.0" encoding="UTF-8"?>
<o><z><x>afdf</x><y><e>dfsdfs</e><e>sdf</e></y></z></o>

Notice that

  • element order has changed. It seems to sort the sub elements while serializing the xml.
  • We have some additional o and e elements inserted

Are there any settings I am missing with json-lib to prevent these two issues?

I did notice that a javascript library https://code.google.com/p/x2js/ seems to work well (albeit other issues), but I am looking for one that is already available in java. I want one that preserves xml structure along with element order. My XML documents do satisfy the two conditions above on subelements.

1

There are 1 answers

0
Christophe On

Not sure that it would still help now but I can do that by using another library : the one from http://www.json.org/

import org.json.JSONObject;
import org.json.XML;

String xmlString = "<z><y>dfsdfs</y><y>sdf</y><x>afdf</x></z>";
System.out.println("Initial XML : " + xmlString);
JSONObject jsonObj = (XML.toJSONObject(xmlString));
System.out.println("Converted JSON : " + jsonObj.toString());
System.out.println("Back to converted XML : " + XML.toString(jsonObj));

You'll need this in your pom if you're using maven :

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20140107</version>
</dependency>