Groovy将两个json与未知节点名称和值进行比较

Mic*_*rdy 5 grails groovy json jsonslurper

我有一个休息API来测试,我必须比较两个json响应.您可以在下面找到该文件的结构.要比较的两个文件应包含相同的元素,但顺序可能不同.不幸的是,名称,类型(简单,数组)和键数(root,nodeXYZ)也是未知的.

{"root": [{
   "node1": "value1",
   "node2": "value1",
   "node3":    [
            {
         "node311": "value311",
         "node312": "value312"
      },
            {
         "node321": "value321",
         "node322": "value322"
      }
   ],
   "node4":    [
            {
         "node411": "value411",
         "node412": "value413",
         "node413": [         {
            "node4131": "value4131",
            "node4132": "value4131"
         }],
         "node414": []
      }
      {
         "node421": "value421",
         "node422": "value422",
         "node423": [         {
            "node4231": "value4231",
            "node4232": "value4231"
         }],
         "node424": []
      }]
   "node5":    [
      {"node51": "value51"},
      {"node52": "value52"},
   ]
}]}
Run Code Online (Sandbox Code Playgroud)

我在Groovy中 找到了一些有用的信息 - 比较两个JSON对象(相同的结构)并返回包含差异的ArrayList 从Json Response Groovy 获取节点:如何使用键的值搜索json并在groovy中找到它的子节点 但我无法将它组合到解决方案.我认为解决方案可能如下所示:

take root
get root children names
check if child has children and get their names
do it to the lowest leve child
Run Code Online (Sandbox Code Playgroud)

有了所有名称,比较应该很容易(我猜)不幸的是我没有设法获得根目录下的密钥

tim*_*tes 6

只需比较啜饮的地图:

def map1 = new JsonSlurper().parseText(document1)
def map2 = new JsonSlurper().parseText(document2)

assert map1 == map2
Run Code Online (Sandbox Code Playgroud)

  • 如果相应文档中的 Json 字段不按顺序限制此方法的有用性,则断言将不起作用。 (2认同)

Jos*_*ček 5

试试 JSONassert 库:https : //github.com/skyscreamer/JSONassert。然后你可以使用:

JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT)
Run Code Online (Sandbox Code Playgroud)

你会得到格式很好的增量,比如:

java.lang.AssertionError: Resources.DbRdsLiferayInstance.Properties.KmsKeyId
Expected: kms-key-2
     got: kms-key
Run Code Online (Sandbox Code Playgroud)