首页 > 解决方案 > 放心 Groovy GPath 过滤掉结果

问题描述

我试图在“dependentPreferences”中返回“description”的值,其中响应满足两个条件:首先,检查名称是否为“John Smith”,然后检查首选项中的“图像”是否等于“papaya.jpg” .

响应正文如下:

[    
    {
        "id": 1,
        "name": "John Smith",
        "description": null,
        "shortDescription": "No recorded interests.",
        "alias": "JS",
        "preferences": [
            {
                "id": 1,
                "description": "likes candy and papaya",
                "image": "papaya.jpg",
                "name": "Papaya",
                "dependentPreferences": [
                    {
                        "id": 1,
                        "description": "Fruit must be ripe",
                        "image": "ripe-papaya.jpg",
                        "name": "pap"
                    }
                ]
            }
         ]
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "description": null,
        "shortDescription": "No recorded interests.",
        "alias": "JS",
        "preferences": [
            {
                "id": 1,
                "description": "likes candy and papaya",
                "image": "papaya.jpg",
                "name": "Papaya",
                "dependentPreferences": [
                    {
                        "id": 1,
                        "description": "Candy must be Skittles",
                        "image": "Skittles.jpg",
                        "name": "skt"
                    }
                ]
            }
         ]
    }
]

到目前为止,我已经尝试过这样的事情:

response.jsonPath().getString("find { it.name == 'John Smith' }.preferences.find {it.image == 'papaya.jpg'}.dependentPreferences.description 

但它抱怨语法。我知道这部分代码可以找到图像:

response.jsonPath().getString("find { it.name == 'John Smith' }.preferences.image

但我在构建第二个条件时遇到了麻烦。任何帮助,将不胜感激。

标签: groovyrest-assuredgpath

解决方案


这里的工作示例。这对我有用:

def endpoint = "http://localhost:3130/ids.json"
def jsonResponse = get(endpoint).then().contentType(ContentType.JSON).extract().response()
def path = jsonResponse.jsonPath()

def result = path.getString("find { it.name == 'John Smith' }.preferences.find {it.image == 'papaya.jpg'}.dependentPreferences.description")

虽然说实话:在 JSON 中,dependentPreferences一个对象数组,所以如果数据与呈现的不同,就有可能出错。


推荐阅读