[英]How to map values of a json object without knowing about the format?
I have the following programming requirement:我有以下编程要求:
problem: Given two JSONs A and B, if the fields x,y,z in JSON A match the fields i,o,p in B return true else false.问题:给定两个 JSON A 和 B,如果 JSON A 中的字段 x,y,z 与 B 中的字段 i,o,p 匹配,则返回 true,否则返回 false。
approach: I want to stay away from building a matching engine that depends on the json's format.方法:我想远离构建依赖于 json 格式的匹配引擎。 I don't want to format the jsons by using pojos and then do object matching.
我不想使用 pojos 格式化 json,然后进行 object 匹配。 My approach is to convert all the jsons into a hash map and then specify the location of the fields by using a string:
我的方法是将所有 json 转换为 hash map 然后使用字符串指定字段的位置:
Example: money -> a,b,c示例:金钱 -> a,b,c
{
a :
{
b : {
c: {
money : "100"
}
}
}
}
However this approach seems to be a bit tricky as we have to take into account collections.然而,这种方法似乎有点棘手,因为我们必须考虑 collections。 I have to cover all of the edge cases.
我必须涵盖所有的边缘情况。 Is there any spring library or java tool I can use to fulfill this purpose?.
是否有任何 spring 库或 java 工具可以用来实现此目的?
There are many libraries being used for this purpose.有许多库用于此目的。
The most popular one is com.google.gson最受欢迎的是com.google.gson
Usage:用法:
JsonObject jo = (JsonObject)(jsonParser.parse("{somejsonstring}");<br>
jo.has("objectProperty") //Check if property exists
jo.get("objectProperty") // returns JsonElement,
jo.get("objectProperty").isJsonArray() // check if the property is the type that want
jo.getAsJsonArray("objectProperty") get the property
You may simplify this work by using im.wilk.vor:Voritem library gitHub or in Maven repository.您可以使用im.wilk.vor:Voritem库gitHub或 Maven 存储库来简化这项工作。
JsonElement je_one = jsonParser.parse("{some_json_string"})
JsonElement je_two = jsonParser.parse("{other_json_string"})
VorItem vi_one = vorItemFactory.from(je_one);
VorItem vi_two = vorItemFactory.from(je_two);
if (vi_one.get("a.b.c").optionalLong().isPresent() ) {
return vi_one.get("a.b.c").optionalLong().equals(vi_one.get("i.o.p").optionalLong())
}
return false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.