Klam
Klam

Reputation: 143

mantaining order of CSV to JSONArray (with Java org.json lib)

I want to put in a JSONArray the values of a CSV, which i can do now with the following code, but the JSONArray does not have the same order my CSV String has, can someone please help? I'm using org.json.

InputStream is = file.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String inputStr, csv = "";

while ((inputStr = br.readLine()) != null){
    csv += inputStr +"\n";
}

JSONArray array = CDL.toJSONArray(csv);

I did not find an easier way to convert the CSV to a JSONArray, the csv String is in the right order and the array is created OK except the array is un-ordered, thanks in advance for any suggestion that might help.

I saw this post but it's kind of backwards of what i need (JSONArray to CSV) Keep the order of the JSON keys during JSON conversion to CSV

Upvotes: 0

Views: 1523

Answers (1)

Hot Licks
Hot Licks

Reputation: 47739

If you enter:

A, B, C
1, 2, 3
4, 5, 6

that will be turned into JSON something like:

[
 { "A":"1", "B":"2", "C":"3" }
 { "A":"4", "B":"5", "C":"6" }
                              ]

However, the values for A, B, and C may come out in any order (not even necessarily the same from one row to the next). There is nothing you can do about this -- it's part of the definition of JSON.

Upvotes: 0

Related Questions