如何在 Groovy 中访问和循环嵌套 Json

问题描述 投票:0回答:1

我正在尝试访问和循环 Groovy 中的嵌套 Json 以进行测试,该文件保存在文件中 下面是结构是怎样的

{
  "dunsNumber": 0,
  "branches": 25,
  "url": "www.nbch.com.com",
  "address": {
    "continentId": 5,
    "continentName": "South & Central America",
    "countryId": 20,
    "countryName": "Brasil"
  },
  "parentOrganizations": [
    {
      "parentType": "IMMEDIATE",
      "name": "abcde",
      "dunsNumber": "12345",
      "address": {
        "continentId": 5,
        "continentName": "Europe",
        "countryId": 33,
        "countryName": "France"
      }
  ]
}

我只需要为节点和 parentOrganizations.address 中的键 continentName 和 coutryName 设置新值

"address": {
        "continentId": 5,
        "continentName": "South & Central America",
        "countryId": 33,
        "countryName": "Argentina",

下面是我的方法

def raw = loadResourceContent("createOrganization1.json") --> loading the Json file
def body = new JSONObject(raw)
                .put("dunsNumber", dunsNumberUnique) //--> I I am using a unique value 
                 .put("name",organizatioNameUnique) //--> random Organization name
                 .put("countryName","Argentina") //--> Here It would add new entry in the parent Node.
                 .toString()

感谢您的帮助,顺便说一句,我是 groovy 和测试方面的新手。

spock jsonobjectrequest groovy-grape
1个回答
0
投票

也许您想阅读有关如何处理 JSON 的 Groovy 手册:

https://groovy-lang.org/processing-json.html

你可以这样做:

package de.scrum_master.stackoverflow.q75817755

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

def json = '''{
  "dunsNumber": 0,
  "branches": 25,
  "url": "www.nbch.com.com",
  "address": {
    "continentId": 5,
    "continentName": "South & Central America",
    "countryId": 20,
    "countryName": "Brasil"
  },
  "parentOrganizations": [
    {
      "parentType": "IMMEDIATE",
      "name": "abcde",
      "dunsNumber": "12345",
      "address": {
        "continentId": 5,
        "continentName": "Europe",
        "countryId": 33,
        "countryName": "France"
      }
    }
  ]
}'''

Map parsed = new JsonSlurper().parseText(json)
parsed.parentOrganizations[0].tap {
  dunsNumber = 424242
  name = "ACME Inc."
  address.continentName = "South & Central America"
  address.countryName = "Argentina"
}
println JsonOutput.prettyPrint(JsonOutput.toJson(parsed))

控制台日志说:

{
    "dunsNumber": 0,
    "branches": 25,
    "url": "www.nbch.com.com",
    "address": {
        "continentId": 5,
        "continentName": "South & Central America",
        "countryId": 20,
        "countryName": "Brasil"
    },
    "parentOrganizations": [
        {
            "parentType": "IMMEDIATE",
            "name": "ACME Inc.",
            "dunsNumber": 424242,
            "address": {
                "continentId": 5,
                "continentName": "South & Central America",
                "countryId": 33,
                "countryName": "Argentina"
            }
        }
    ]
}

这就是你的想法吗?

© www.soinside.com 2019 - 2024. All rights reserved.