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

时间:2015-10-29 09:48:59

标签: json grails groovy jsonslurper

我有一个测试的rest 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"},
   ]
}]}

我在中找到了一些有用的信息 Groovy - compare two JSON objects (same structure) and return ArrayList containing differences Getting node from Json Response Groovy : how do i search json with key's value and find its children in groovy 但我无法将它与解决方案结合起来。 我认为解决方案可能如下所示:

take root
get root children names
check if child has children and get their names
do it to the lowest leve child

所有名称都比较应该很容易(我猜) 不幸的是,我没有设法在root下获取密钥

2 个答案:

答案 0 :(得分:6)

只需比较潦草的地图:

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

assert map1 == map2

答案 1 :(得分:2)

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

main

你将得到格式良好的增量,如:

JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT)