Monday, 29 December 2014

Is it possible to maintain ordering in JSON while converting it from xml and vice versa



I need to convert XML to JSON and then after applying some business logic need to reconvert back in XML, But when i try to convert a XML to JSON and then reconvert back the JSON back to XML I am getting its attributes in Different order.


Eg Following XML


<breakfast_menu><food><name>Belgian Waffles</name><price>$5.95</price></food></breakfast_menu>


is converted to following JSON



{"breakfast_menu":{"food":{"price":"$5.95","name":"Belgian Waffles"}}}


and is reconverted to following XML



<breakfast_menu><food><price>$5.95</price><name>Belgian Waffles</name></food></breakfast_menu>


As there is name tag is replaced by price tag .


Is there any way so that we can maintain ordering so the conversion and reconversion produce same output .



import org.json.JSONException;
import org.json.JSONObject;


import org.json.XML;



public class XmlToJson {


public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<breakfast_menu>\n" +
"<food>\n" +
"<name>Belgian Waffles</name>\n" +
"<price>$5.95</price>\n" +
"</food>\n" +
"</breakfast_menu>";

public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonString = xmlJSONObj.toString();
System.out.println(jsonString);
System.out.println("================================");
JSONObject jsonObj = new JSONObject(jsonString);
String s1 = XML.toString(jsonObj);

System.out.println(s1);
s1 = s1.replace("\n", "").replace("\r", "");
TEST_XML_STRING = TEST_XML_STRING.replace("\n", "").replace("\r", "");
System.out.println("================================");
System.out.println(TEST_XML_STRING);
System.out.println("================================");

System.out.println(s1.equals(TEST_XML_STRING));



} catch (JSONException je) {
System.out.println(je.toString());
}
}


}


No comments:

Post a Comment