本文介绍了按日期字段YYYY-MM-DD hh-mm-ss.sss对JSONArray字符串排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式化为这样的字符串的JSONArray:
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"}]
有没有一种有效的方法可以按时间顺序对所有JSON对象进行排序?
Is there some efficient way to sort all the JSON objects in chronological order?
推荐答案
假设您在 JSONObject
实例中只有一个条目,则可以:
Assuming that you have only one entry in your JSONObject
instances, you could:
- 从
JSONArray
中提取 - 通过比较
JSONObject
s的第一个键 对 - 然后创建一个新的
JSONArray
或在旧的JSONArray
中重新设置值.
JSONObject
实例 JSONObject
的数组进行排序- Extract the
JSONObject
instances from theJSONArray
, - Sort the array of
JSONObject
by comparing the first key of theJSONObject
s, - Then create a new
JSONArray
or re-set values in the oldJSONArray
.
类似这样的东西:
// 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"}]
这篇关于按日期字段YYYY-MM-DD hh-mm-ss.sss对JSONArray字符串排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!