Groovy-解析仅响应中存在某些值的JSON [英] Groovy - Parse JSON where only certain values exists in response

查看:140
本文介绍了Groovy-解析仅响应中存在某些值的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JsonSlurper解析具有重复对象的JSON响应,以与JDBC查询进行比较.但是,我只想比较对象中存在某些值的对象.

I am trying to parse a JSON response that has repeating objects with JsonSlurper to compare to a JDBC query. However, I only want to compare objects where a certain values exist within that object.

如果我收到这样的答复,我将如何仅分析该国家等于美国或加拿大的对象,从而忽略其他任何内容?

If I had a response that looks like this, how would I only parse the objects where the country equals USA or Canada, therefore ignoring anything else?

{
    "info": [{
        "name": "John Smith",
        "phone": "2125557878",
        "country": {
            "value": "USA"
        }
    },
    {
        "name": "Jane Smith",
        "phone": "2125551212",
        "country": {
            "value": "USA"
        }
    },
    {
        "name": "Bob Jones",
        "phone": "4165558714",
        "country": {
            "value": "Canada"
        }
    },
    {
        "name": "George Tucker",
        "phone": "4454547171",
        "country": {
            "value": "UK"
        }
    },
    {
        "name": "Jean Normand",
        "phone": "4454547171",
        "country": {
            "value": "France"
        }
    }]
}

这就是我的常规:

def jsonResponse = context.expand('${RESTRequest#Response}')
def parsedJson = new JsonSlurper().parseText(jsonResponse)
def info = parsedJson.info

    def jsonDataObjects = []
    info.each { json ->
        jsonDataObjects.add(Model.buildJSONData(json))
    }

我正在构建需要与数据库进行比较的元素的集合.如何仅将info.country.value =美国或加拿大添加到该集合中?

I am building a collection of the elements that I need to compare to a database. How do I only add to that collection where the info.country.value = USA or Canada?

我尝试像这样使用.findAll来测试是否可以仅通过以下国家之一对其进行过滤:

I tried using .findAll like this just to test if I could get it to filter by just one of the countries:

def info = parsedJson.info.country.findAll{it.value == "USA"}

但是,当我这样做时,仅保留value字段.我从解析中丢失了姓名和电话.

But, when I do that, only the value field is kept. I lose the name and phone from the parse.

在此先感谢您的帮助.

推荐答案

您尝试过

def info = parsedJson.info.findAll{it.country.value == "USA"}

?

这篇关于Groovy-解析仅响应中存在某些值的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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