Java的JSON庫(kù)是很方便的,可以將JSON字符串轉(zhuǎn)化為Java對(duì)象以及將Java對(duì)象轉(zhuǎn)化為JSON字符串。但如果涉及到時(shí)間字段,需要進(jìn)行時(shí)間排序的操作,就需要對(duì)JSON中的時(shí)間進(jìn)行處理。
// JSON字符串 String jsonStr = "[{\"name\":\"John\",\"birthday\":\"1990-12-05T08:30:00Z\"},{\"name\":\"Alice\",\"birthday\":\"1988-09-23T11:00:00Z\"}]"; // 將JSON字符串解析為Java對(duì)象 ObjectMapper mapper = new ObjectMapper(); List<Map<String, Object>> userList = mapper.readValue(jsonStr, List.class); // 對(duì)時(shí)間進(jìn)行排序 Collections.sort(userList, new Comparator<Map<String, Object>>() { @Override public int compare(Map<String, Object> o1, Map<String, Object> o2) { String birthday1 = (String) o1.get("birthday"); String birthday2 = (String) o2.get("birthday"); LocalDateTime localDateTime1 = LocalDateTime.parse(birthday1, DateTimeFormatter.ISO_ZONED_DATE_TIME); LocalDateTime localDateTime2 = LocalDateTime.parse(birthday2, DateTimeFormatter.ISO_ZONED_DATE_TIME); return localDateTime1.compareTo(localDateTime2); } }); // 將Java對(duì)象轉(zhuǎn)化為JSON字符串 String sortedJsonStr = mapper.writeValueAsString(userList); System.out.println(sortedJsonStr);
上面的代碼中,首先將JSON字符串解析為Java對(duì)象,并對(duì)時(shí)間進(jìn)行排序。這里用到了Java 8 的日期時(shí)間API,將字符串解析為L(zhǎng)ocalDateTime對(duì)象,并調(diào)用compareTo方法,實(shí)現(xiàn)時(shí)間比較。最后將排序后的Java對(duì)象轉(zhuǎn)化為JSON字符串。
總之,Java中對(duì)JSON進(jìn)行時(shí)間排序的操作并不難,只需要對(duì)時(shí)間字符串進(jìn)行解析,并比較時(shí)間即可。