Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No insertion orderr is preserved while converting from xml to json using org.json.XML.toJSONObject(xmlStirng)

I am using a dynamic data structure for my project. So instead of a predefined class I am using java.util.LinkedHashMap to store my dynamic data and preserve my insertion order as well.

I am able to convert the map to json and get the map and back from Json using “.

fasterxml.jackson.databind.ObejctMapper mapper; 

LinkedHashMap<String, Object> map =
            mapper.readValue(json, new TypeReference<LinkedHashMap<String, Object>>() {});

String json = mapper.writeValueAsString(map);

I am trying to do some XSLT transformation on my map data. So I also need to transform from xml to map and map to xml. As there is no direct method to convert these I wrote my own utility for map to xml.
and to convert from xml to map I used -> org.json.JSONObject. I first convert the xml to json using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

org.json.XML.toJSONObject(xmlstring)

and can convert the json to map easily using object mapper.

But the problem here is I am loosing the insertion order which is crucial for my data.

How can I convert my data from xml to json so that the insertion order is preserved.

>Solution :

Thats a superb idea to use LinkedHashMap for dynamic data structure.

However JSONObject internally uses HashMap to create the json. So it looses the insertion order.

public JSONObject() {
        // HashMap is used on purpose to ensure that elements are unordered by
        // the specification.
        // JSON tends to be a portable transfer format to allows the container
        // implementations to rearrange their items for a faster element
        // retrieval based on associative access.
        // Therefore, an implementation mustn't rely on the order of the item.
        this.map = new HashMap<String, Object>();
    }

So If you can override the JSONObject your problem will be solved.

Enjoy!!!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading