Vish - 2013-12-27

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 http://www.xml.com/lpt/a/1658

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?