Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverted order of JSON elements in Java after XML conversion

Tags:

java

json

I'm using the JSON in Java for the transformation of XML to JSON. I have the problem that this implementation is inverting all child elements.

When I pass this XML:

<Person><Child1>a</Child1><Child2>b</Child2></Person>

I will end up with a JSON having the childs inverted:

{"Person":{"Child2":"b", "Child1":"a"}}

My Java code:

JSONObject jsonObject= XML.toJSONObject("<Person><Child1>a</Child1><Child2>b</Child2></Person>");
String myJSONString = jsonObject.toString(4);

How to transform to JSON with keeping the order of the elements (like in XML)?

like image 391
FiveO Avatar asked Sep 25 '14 08:09

FiveO


1 Answers

So my question. How to transform to JSON with keeping the order?

With the current official JSONObject, this is not possible. The API makes it very clear:

A JSONObject is an unordered collection of name/value pairs.

But, there might be a quick workaround for your problem. As from what I've investigated in the JSONObject source code, you can see that it uses a HashMap internally, and as you know HashMap doesn't keep any order.

public JSONObject() { this.map = new HashMap<String, Object>(); }

You have 2 alternatives:

  1. Modify the current JSONObject source code so that the map is initialized with a LinkedHashMap. A LinkedHashMap is an implementation of the Map interface, with predictable iteration order:

    public JSONObject() {
          this.map = new LinkedHashMap<String, Object>();
    }
    
  2. Make your own custom class which extends JSONObject but uses a LinkedHashMap internally. Notice that you still have to make some changes in JSONObject.

    public class JSONObject {
    
        //private final Map<String,Object> map; // current approach
        //you have to remove final modifier and either add a getter or make it protected. I'll choose the change modifier to protected in this case.
        protected Map<String,Object> map;
    
    }
    
    public class JSONObjectOrdered extends JSONObject {
        public JSONObjectOrdered(){
            this.map = new LinkedHashMap <String, Object>();
        } 
    }
    
like image 81
Daniel Avatar answered Oct 31 '22 05:10

Daniel