【发布时间】:2021-08-14 20:37:13
【问题描述】:
我在使用 Guava 的 Maps.difference 时遇到了一些问题
现在,使用此代码比较来自两个不同 json 的两个 HashMap:
//Create maps from the given jsons
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> map1 = gson.fromJson(jsonObject1, type);
Map<String, Object> map2 = gson.fromJson(jsonObject2, type);
//Flatten the maps
Map<String, Object> leftFlatMap = FlatMap.flatten(map1);
Map<String, Object> rightFlatMap = FlatMap.flatten(map2);
//Check differences between both maps
MapDifference<String, Object> difference = Maps.difference(leftFlatMap, rightFlatMap);
一切正常,并且(几乎)正确比较了所有元素。 问题是当 HashMap 中的一个元素是一个映射数组并且元素相同但顺序不同时。像这样:
第一个 JSON:
{ "body":[
{
"primitive":"VALUE",
"jsonArray":[
{
"element":83284180
},
{
"anotherElement":20832841804
}
]
}
]
}
第二个 JSON:
{
"body":[
{
"primitive":"VALUE",
"jsonArray":[
{
"anotherElement":20832841804
},
{
"element":83284180
}
]
}
]
}
如您所见,element 和 anotherElement 的值相同,但由于它们在数组中出现的顺序不同,因此差异显示错误。
之前有没有可能对数组进行排序?或任何其他解决方案?
提前致谢!!
【问题讨论】:
-
FlatMap.flatten()来自哪里? -
如果您可以将每个列表映射到一个集合,您就可以克服这个问题。
-
我使用 FlatMap 只是为了使结果更具可读性,如果我不使用它,结果将类似于:
body: ([{primitive=VALUE, jsonArray=[{element=8.328418E7}, {anotherElement=2.0832841804E10}]}], [{primitive=VALUE, jsonArray=[{anotherElement=2.0832841804E10}, {element=8.328418E7}]}])而使用 Flatmap:/body/0/jsonArray/0/element: 8.328418E7 /body/0/jsonArray/1/anotherElement: 2.0832841804E10
标签: java json hashmap gson guava