0

I have a JSONArray formatted as a string like this:

[{"2016-11-09 19:01:59.649":"someone@email.com::example message"},
{"2016-11-09 19:01:05.542":"someone@email.com::another example"},
{"2016-11-09 19:02:01.394":"someother@gmail.com::another one"}]

Is there some efficient way to sort all the JSON objects in chronological order?

Andrew
  • 358
  • 10
  • 23

1 Answers1

0

Assuming that you have only one entry in your JSONObject instances, you could:

  1. Extract the JSONObject instances from the JSONArray,
  2. Sort the array of JSONObject by comparing the first key of the JSONObjects,
  3. Then create a new JSONArray or re-set values in the old JSONArray.

Something like this:

// Build the source JSONArray
JSONArray array = new JSONArray();
array.put(
    new JSONObject("{\"2016-11-09 19:01:59.649\":\"someone@email.com::example message\"}")
);
array.put(
    new JSONObject("{\"2016-11-09 19:01:05.542\":\"someone@email.com::another example\"}")
);
array.put(
    new JSONObject("{\"2016-11-09 19:02:01.394\":\"someother@gmail.com::another one\"}")
);

// Extract the JSONObjects
JSONObject[] objects = new JSONObject[array.length()];
for (int i = 0; i < objects.length; i++) {
    objects[i] = array.getJSONObject(i);
}
// Sort the array of JSONObjects
Arrays.sort(
    objects,
    (JSONObject o1, JSONObject o2) ->
        ((String)o1.keys().next()).compareTo((String)o2.keys().next())
);
// Build a new JSONArray from the sorted array
JSONArray array2 = new JSONArray();
for (JSONObject o : objects) {
    array2.put(o);
}
System.out.println(array2);

Output:

[{"2016-11-09 19:01:05.542":"someone@email.com::another example"},{"2016-11-09 19:01:59.649":"someone@email.com::example message"},{"2016-11-09 19:02:01.394":"someother@gmail.com::another one"}]
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • 1
    Thanks, it looks pretty good! I will try it out in a few moments and accept it as the correct answer as soon as it works. – Andrew Nov 09 '16 at 19:01