Groovy 如果某项等于

Groovy remove list if an item is equal to

我有这个 json:

{
    "books": [
        {
            "bookId": "1",
            "bookName": "name1",
            "bookYear": "2010"
        },
        {
            "bookId": "2",
            "bookName": "name2",
            "bookYear": "2010"
        }
    ]
}

我想删除包含 "bookId": "1" 的列表 结果应该是:

{
    "books": [
        {
            "bookId": "2",
            "bookName": "name2",
            "bookYear": "2010"
        }
    ]
}

我试过这个代码:

import groovy.json.JsonSlurper
import groovy.json.JsonOutput


JsonSlurper slurper = new JsonSlurper()
String jsonString = vars.get("jsonOutput")
def parsedJson = slurper.parseText(jsonString)

log.info("Json before: " + jsonString)

int num = parsedJson.books.size()
for(int i=0;i<parsedJson.books.size();i++){
    parsedJson.books[i].values().removeAll(value -> value.equals("1"))
}

def json = JsonOutput.toJson(parsedJson)
log.info("Json after: " + json.toString())

但它只从列表中删除“bookId”:

Json before: {"books":[{"bookId":"1","bookName":"name1","bookYear":"2010"},{"bookId":"2","bookName":"name2","bookYear":"2010"}]}

Json after: {"books":[{"bookName":"name1","bookYear":"2010"},{"bookId":"2","bookName":"name2","bookYear":"2010"}]}

拜托,你能帮我吗?

您可以像这样过滤图书列表:

def parsedJson = slurper.parseText(jsonString)

parsedJson.books = parsedJson.books.findAll { it.bookId != '1' }

def json = JsonOutput.toJson(parsedJson)