0

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

Community
  • 1
  • 1
Klam
  • 161
  • 1
  • 15
  • Well, of course, what you're building is not a CSV (comma-separated value) string. – Hot Licks Oct 29 '14 at 15:53
  • You'd be better off building a List and converting that. – Hot Licks Oct 29 '14 at 15:55
  • What do you mean it's not a CSV String? the string is exactly what the cvs file is only in String format. Can you please provide an example of converting the List? toJASONArray does not take a List. – Klam Oct 29 '14 at 16:01
  • OK, so you're entering entire CSV lines in one data entry? If so, the values will end up in "objects" in the JSON "array", with one input line (as an "object") per array entry. – Hot Licks Oct 29 '14 at 16:04
  • (And JSON "objects" are not ordered.) – Hot Licks Oct 29 '14 at 16:05
  • Correct, it's not ordered, so that's the question. How do i change this code to make it ordered? you mentioned Lists but CDL.toJASONArray does not take Lists, so i'm not sure what you had in mind, if you don't mind sharing, that'd be appreciated. – Klam Oct 29 '14 at 16:24
  • JSON "objects" aren't ordered. You can't do anything to change that. – Hot Licks Oct 29 '14 at 16:25

1 Answers1

0

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.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151