Groovy - compare two JSON objects (same structure) and return ArrayList containing differences

不羁岁月 提交于 2020-01-02 21:56:56

问题


I have two JSON objects of the same structure - an original and one which I want to compare it to. There is only one level of information (i.e nothing has any children).

I want to compare the two and remember which fields, if any, were different by storing the key in the secondDifferingFields ArrayList.

    def secondDifferingFields = new ArrayList()
    orignialJSON.each {
        print "original:"+it.value+":VS:"+secondJSON.it+":second"
        if (it.value != secondJSON.it){
                secondDifferingFields.add(it)
        }
    }

I can see that I am iterating through the values of the originalJSON, but am unsure on how to access the same key's value (if that's the right wording) in the secondJSON to be able to then compare them. With the print line I always see

original:XYZ:VS:null:second


回答1:


You are comparing always against secondJSON.it (it here is just a String key, and since there is no value for this key, you get null).

You will have to use:

secondJSON.get(it.key)
// or secondJSON."$it.key"

to access the key from the other map. Be aware, that you might want to check with containsKey if there actually is an entry, if you have valid null values in the map.

Using non-existing properties on a map in groovy will just try to look up that string key in the map.

assert [:].it==null // key `String it` does not exist
assert [:].SevenDrunkenNights==null // same here
assert [it:1].it==1 // now it does
assert [:].get('it')==null // same same for `get`
assert [it:1].get('it')==1


来源:https://stackoverflow.com/questions/30600642/groovy-compare-two-json-objects-same-structure-and-return-arraylist-containi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!