【问题标题】:Sorting a JSONArray string by its date field YYYY-MM-DD hh-mm-ss.sss [duplicate]按日期字段 YYYY-MM-DD hh-mm-ss.sss 对 JSONArray 字符串进行排序 [重复]
【发布时间】:2017-03-23 15:50:32
【问题描述】:

我有一个 JSONArray,格式如下:

[{"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"}]

是否有一些有效的方法可以按时间顺序对所有 JSON 对象进行排序?

【问题讨论】:

  • 我永远不会将日期字段作为JSONObject 中的键。我认为这会搞砸你将如何使用它。
  • @Andrew:你要排序多少个对象?
  • @walkeros 最多 200 个对象,仅此而已

标签: java json sorting date


【解决方案1】:

假设您的 JSONObject 实例中只有一个条目,您可以:

  1. JSONArray中提取JSONObject实例,
  2. 通过比较JSONObjects的第一个键,对JSONObject的数组进行排序,
  3. 然后创建一个新的JSONArray 或在旧的JSONArray 中重新设置值。

类似这样的:

// 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);

输出:

[{"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"}]

【讨论】:

  • 谢谢,看起来不错!稍后我会尝试一下,并在它起作用后立即接受它作为正确答案。
猜你喜欢
  • 2016-12-25
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2020-05-10
相关资源
最近更新 更多