I am using the JSON library provided here http://www.json.org/java/index.html to convert a json string I have to CSV. But the problem I have is, the order of the keys is lost after conversion.
This is the conversion code:
JSONObject jo = new JSONObject(someString);
JSONArray ja = jo.getJSONArray("items");
String s = CDL.toString(ja);
System.out.println(s);
This is the content of "someString":
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
]
}
This is the result:
WO,QU,WR,QA,NO
hasd,asd,qwe,end,qwer
While what I expect is to keep the order of the keys:
WR,QU,QA,WO,NO
qwe,asd,end,hasd,qwer
Is there any way I can have this result using this library? If not, is there any other library that will provide the capability to keep the order of keys in the result?
Apache Wink has OrderedJSONObject. It keeps the order while parsing the String.
The most safe way is probably overriding keys method that is used to generate output:
Just stumbled upon the same problem, I believe the final solution used by the author consisted in using a custom ContainerFactory:
see http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/parser/JSONParser.html#parse(java.io.Reader,org.json.simple.parser.ContainerFactory)
In the real world, an application will almost always have java bean or domain that is to be serialized/de-serialized to/from JSON. Its already mentioned that JSON Object specification does not guarantee order and any manipulation to that behavior does not justify the requirement. I had the same scenario in my application where I needed to preserve order just for the sack of readability purpose. I used standard jackson way to serialize my java bean to JSON:
In order to make the json with an ordered set of elements I just use JSON property annotation in the the Java bean I used for conversion. An example below:
the getObject() used above:
The output shows as per Json property order annotation:
JSONObject.java
takes whatever map you pass. It may beLinkedHashMap
orTreeMap
and it will takehashmap
only when the map is null .Here is the constructor of
JSONObject.java
class that will do the checking of map.So before building a json object construct
LinkedHashMap
and then pass it to the constructor like this ,So there is no need to change the
JSONObject.java
class . Hope it helps somebody .A more verbose, but broadly applicable solution to this sort of problem is to use a pair of data structures: a list to contain the ordering, and a map to contain the relations.
For Example:
You iterate the itemOrder list, and use those to look up the map values. Ordering is preserved, with no kludges.
I have used this method many times.