这是json
[
{
"SUBTASK": {
"id": 10,
"name": "TestMap",
"description": "",
"version":"1.0"
}
},
{
"SUBTASK": {
"id": 23,
"name": "TestMap",
"description": "",
"version":"2.0"
}
},
{
"SUBTASK": {
"id": 12,
"name": "Tree",
"description": "",
"version":"13.0"
}
},
{
"SUBTASK": {
"id": 32,
"name": "Tree",
"description": "",
"version":"10.0"
}
}
]
需要获得SUBTASKS的最新数量 即。过滤最新版本的SUBTASK并尊重名称。
所以最终的json会像:
final:[{"SUBTASK":{"id":12.0,"name":"Tree","description":"","version":"13.0"}},{"SUBTASK":{"id":23.0,"name":"TestMap","description":"","version":"2.0"}}]
我使用下面的java代码:
Java Snippet
public void getLatest(String json) throws Exception {
// converting json to java Object
List<Map<String, Object>> taskList = new Gson().fromJson(json, new TypeToken<List<Map<String, Object>>>() {
}.getType());
Map<String, Object> taskVersionedMap = new HashMap<String, Object>();
for (int i = 0; i < taskList.size(); i++) {
Map<String, Object> processMap = taskList.get(i);
Map<String, Object> process = (Map<String, Object>) processMap.get("SUBTASK");
String process_name = process.get("name").toString() + "_" + process.get("version");
taskVersionedMap.put(process_name, processMap);
for (Map.Entry<String, Object> entry : taskVersionedMap.entrySet()) {
String[] split = entry.getKey().split("_");
double version = Double.parseDouble(split[1]);
String name = split[0];
for (Map.Entry<String, Object> entry2 : taskVersionedMap.entrySet()) {
String[] split_2 = entry2.getKey().split("_");
double version_2 = Double.parseDouble(split_2[1]);
String name_2 = split_2[0];
if (name.equals(name_2)) {
if (version < version_2) {
String removedProcessName = name + "_" + version;
taskVersionedMap.put(removedProcessName, "ignored");
}
}
}
}
}
List<Map<String, Object>> filteredVersionList = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, Object> mapValues : taskVersionedMap.entrySet()) {
if (!mapValues.getValue().toString().equals("ignored")) {
try {
filteredVersionList.add((Map<String, Object>) mapValues.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("final:"+new Gson().toJson(filteredVersionList));
}
上述代码可以提供准确的结果并且非常耗时。
但可以优化代码 因为正在处理的真实数据json将非常强大近500个子任务