Groovy - 比较两个JSON对象(相同的结构)并返回包含差异的ArrayList [英] Groovy - compare two JSON objects (same structure) and return ArrayList containing differences

查看:815
本文介绍了Groovy - 比较两个JSON对象(相同的结构)并返回包含差异的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同结构的JSON对象 - 一个原始的,我想比较它的一个。只有一个级别的信息(即没有任何子级)。

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).

我想比较两个,记住哪些字段in the secondDifferingFields ArrayList。

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)
        }
    }



我可以看到我通过原始JSON的值迭代,我不确定如何访问相同的键的值(如果这是正确的措辞)在secondJSON,以便能够然后比较它们。使用打印行我总是看到

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

原始:XYZ:VS:null:second

original:XYZ:VS:null:second

推荐答案

你正在比较 secondJSON.it it 这里只是一个字符串键,因为这个键没有值,你得到 null )。

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).

你必须使用: p>

You will have to use:

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

从其他地图访问该键。请注意,如果您有有效的 null 值,您可能需要检查 containsKey

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.

在groovy中在地图上使用不存在的属性只是尝试在地图中查找该字符串键。

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

这篇关于Groovy - 比较两个JSON对象(相同的结构)并返回包含差异的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆