Hery Hery - 9 months ago 35
Java Question

Keep the order of the JSON keys during JSON conversion to CSV

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?

Answer Source

Solved.

I used the JSON.simple library from here https://code.google.com/p/json-simple/ to read the JSON string to keep the order of keys and use JavaCSV library from here http://sourceforge.net/projects/javacsv/ to convert to CSV format.