我正在尝试按降序对json字符串中的json数组进行排序。目前,我本人正在编写一个实用程序,该实用程序通过给定的json进行解析,占用要在其中排序的数组。排序相同,使用排序后的数组构造json字符串,然后返回json字符串。
示例我的输入json如下所示:
{
"scan_detail": [
{
"refno": "8242433485",
"status_code": "664",
"updated_date": "2019-04-02 01:02:53"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-02 01:40:34"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-03 13:51:59"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-08 12:45:36"
},
{
"refno": "8242433485",
"status_code": "954",
"updated_date": "2019-04-08 13:11:39"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-02 01:02:53"
}
]
}
我的输出应如下所示:
{
"scan_detail": [
{
"refno": "8242433485",
"status_code": "954",
"updated_date": "2019-04-08 13:11:39"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-08 12:45:36"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-03 13:51:59"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-02 01:40:34"
},
{
"refno": "8242433485",
"status_code": "664",
"updated_date": "2019-04-02 01:02:53"
},
{
"refno": "8242433485",
"status_code": "108",
"updated_date": "2019-04-02 01:02:53"
}
]
}
我正在做以下事情:
但是,在这种情况下,我应该知道输入json的复杂性。我应该知道json中数组的路径以对其进行排序。
我想编写一些通用实用程序来对给定json字符串中的给定数组进行排序。有更好的方法吗?请提示。下面是我尝试过的代码段。
public static LinkedHashMap<String, Object> createHashMapFromJsonString(String json) {
//this retuns the map constructed out of given json
return map;
}
public String convertMapToJson(LinkedHashMap<String, Object> jsonMap){
//this constructs json with given map using gson library
}
public String sortJsonArray(String UnsortedJson){
String sortedJson = "";
try {
//pick up the arrar from the map given out of createHashMapFromJsonString. Sort it by overriding the comparator method. Add the sorted same to map.
// Convert the map to json using convertMapToJson.
return sortedJson;
}
public Comparator<Map<String, Object>> mapComparator = new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> m1, Map<String, Object> m2) {
return getEventDate(m2.get("updated_date").toString()).compareTo(getEventDate(m1.get("updated_date").toString()));
}
};