[英]How to map values of a json object without knowing about the format?
我有以下編程要求:
問題:給定兩個 JSON A 和 B,如果 JSON A 中的字段 x,y,z 與 B 中的字段 i,o,p 匹配,則返回 true,否則返回 false。
方法:我想遠離構建依賴於 json 格式的匹配引擎。 我不想使用 pojos 格式化 json,然后進行 object 匹配。 我的方法是將所有 json 轉換為 hash map 然后使用字符串指定字段的位置:
示例:金錢 -> a,b,c
{
a :
{
b : {
c: {
money : "100"
}
}
}
}
然而,這種方法似乎有點棘手,因為我們必須考慮 collections。 我必須涵蓋所有的邊緣情況。 是否有任何 spring 庫或 java 工具可以用來實現此目的?
有許多庫用於此目的。
最受歡迎的是com.google.gson
用法:
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
您可以使用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.