代码中遇到一个接口传过来的json串,并根据其中一个字段日期排序取最新一组数据
Json数据格式大概为这种,
{
"body":{
"description":"查询成功",
"execution":{
"text1":{
"time":"2016年12月14日",
"datatypeid":102
},"text2":{
"time":"2019年11月14日",
"datatypeid":103
},
"demo1":{
"basic":"测试1",
"time":"2015年7月5日"
},
"demo2":{
"basic":"测试2",
"time":"2016年7月14日"
}
}
}
}
这里分为两大类型text、demo并分别根据time排序分别取最新一条数据。
以下 是实现逻辑代码(小小菜鸟,希望大神们多多指教):
public static void main(String[] args) throws Exception {
//这里我直接读取数据文本文件
String jsonStr = FileUtils.readFileToString(new File("E:\\workspace\\bair_ln.txt"), "UTF-8");
JsonNode jsonNode = JsonUtils.fromJsonString(jsonStr, JsonNode.class);
//定位获取execution json
JsonNode node = jsonNode.get("body").path("execution");
System.out.println("原始报文----------\n"+node);
System.out.println("最后输出----------\n"+visitNode(node));
}
/**
*格式化JsonNode
**/
public static ArrayList visitNode(JsonNode node) {
ArrayList res = new ArrayList();
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
Map m = new HashMap();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
String head = entry.getKey();
JsonNode n = entry.getValue();
m.put(head, n);
}
//likeString("text", m).get(0))模糊匹配包含text字符串的json
res.add(likeString("court_bad", m).get(0));
res.add(likeString("court_executed", m).get(0));
return res;
}
/**
*模糊匹配包含某个字符串,并排序
**/
public static List likeString(String key, Map<String, JsonNode> map) {
List list = new ArrayList();
Iterator it = map.entrySet().iterator();
List l = new ArrayList();
while (it.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) it.next();
if (entry.getKey().indexOf(key) != -1) {
l.add(entry.getValue());
}
}
SortClass sort = new SortClass();
System.out.println("模糊匹配排序前----"+l);//查看排序结果
//时间倒序排序
Collections.sort(l, sort);
System.out.println("模糊匹配排序后----"+l);//查看排序结果
return l;
}
//Comparator 比较日期排序
public static class SortClass implements Comparator<JsonNode> {
@Override
public int compare(JsonNode o1, JsonNode o2){
//这里做了一个替换,可根据需要看需不需要转换
String obj1 = o1.get("time").toString().replace("\"","");
String obj2 = o2.get("time").toString().replace("\"","");
int flag = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
Date d1 = sdf.parse(obj1);
Date d2 = sdf.parse(obj2);
flag = d1.compareTo(d2);
} catch (ParseException e) {
e.printStackTrace();
}
return -flag; // 不取反,则按正序排列
}
}
输出结果为: