有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在不知道格式的情况下映射json对象的值?

我有以下编程要求:

问题: 给定两个JSON A和B,如果JSON A中的字段x、y、z与B中的字段i、o、p匹配,则返回true else false

方法: 我不想构建一个依赖于json格式的匹配引擎。我不想使用POJO格式化JSON,然后进行对象匹配。我的方法是将所有JSON转换为哈希映射,然后使用字符串指定字段的位置:

例如: 金钱->;a、 b,c

{
  a :
   {
      b : {
         c: {
           money : "100"
         }
       }
    }
}

然而,这种方法似乎有点棘手,因为我们必须考虑收藏。我得负责所有的边缘案件。是否有任何spring库或java工具可用于实现此目的


共 (2) 个答案

  1. # 1 楼答案

    有许多图书馆正用于此目的
    最受欢迎的是com。谷歌。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
    
  2. # 2 楼答案

    你可以使用im来简化这项工作。威尔克。vor:VoritemgitHub或在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;