如何从使用Groovy嵌套在JSON中的ArrayList获取密钥并更改其值 [英] How to get key from ArrayList nested in JSON using Groovy and change its value

查看:219
本文介绍了如何从使用Groovy嵌套在JSON中的ArrayList获取密钥并更改其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够找到关键字 quote.orderAttributes [0] .attributeDetail.name 并将其值设置为 null 或我想要的任何其他值。我只需要为任何列表中的第一个元素执行此操作,以便选择[0]就可以了。我希望能够使用诸如'quote.orderAttributes.attributeDetail.name'之类的路径。但鉴于目前为止所花费的时间,请告知任何更好的方法。



以下是Json:

  {
source:source,
orderId:null,
Version:null,
quote:{
globalTransactionId:k2o4-6969-1fie-poef,
quoteStatus:未上传,
events:{
eventDescription:事件描述,
eventTypeName:事件类型
},
someReport:{
acceptResultsFlag:Y,
orderDate:2017-06-14,
orderStatus:string
},
anotherReport:{
id:627311,
orderDate:2017-06-14
},
attributes:[
{
appliedFlag:Y,
attributeDetail:{
name:name1,
value:value1
},
attributeName:attribute1
},
{
appliedFlag :N,
attributeDetail:{
name:name2,
value:value2
},
attributeName :attribute2
}
],
orderAttributes:[
{
appliedFlag:Y,
attributeDetail:{
name:name3,
value:value3
},
attributeName:orderAttribute1
},
{
appliedFlag:N,
attributeDetail:{
name:name4,
value:value4
} ,
attributeName:orderAttribute2
}
]
}
}

我知道以下工作,但要求我知道哪些对象是 ArrayList ,并指定它的 [0] 索引项目:

  def input = new File(src / test / resources /ShortExample.json)
def json = new JsonSlurper()。parse(in put)
def option1 = json ['quote'] [attributes] [0] [attributeDetail] [name]
println option1

//或这
//其中csvData.fullPath = quote.orderAttributes.attributeDetail.name
$ b def(tkn1,tkn2,tkn3,tkn4)= csvData.fullPath.tokenize('。')
def option2 = json [$ tkn1] [$ tkn2] [0] [$ tkn3] [$ tkn4]
println option2



我希望能够:

  def input = new File(src / test / resources / ShortExample.json)
def json = new JsonSlurper()。parse(input)
def changeValueTo = null
def(tkn1, tkn2,tkn3,tkn4)= csvData.fullPath.tokenize('。')
json [$ tkn1] [$ tkn2] [$ tkn3] [$ tkn4] = changeValueTo

我尝试在这里使用递归实现许多示例,创建MapsOrCollections的方法可以识别对象是,然后搜索它的关键或价值,甚至蹦床的例子。



如果你能指出我一篇很好的文章来解释序列化和反序列化,那么也会非常感激。

解决方案

您可以直接访问和修改任何嵌套的JSON对象字段,例如

  json.quote.attributes [0] .attributeDetail.name = null 

这是可能的,因为 new JsonSlurper()。parse(input)返回一个 groovy.json.internal.LazyMap 对象。 Groovy允许您使用点符号访问和修改任何 Map 条目,例如

  Map< String,Map< String,Integer>> map = [
lorem:[ipsum:1,dolor:2,sit:3]
]

println map.lorem.ipsum //打印'1'
map.lorem.ipsum = 10
println map.lorem.ipsum //打印'10'

您可以对您的示例应用相同的方法,例如

  import groovy.json.JsonSlurper 

String input ='''{
source:source,
orderId:null,
Version:null,
quote:{
globalTransactionId:k2o4-6969-1fie-poef,
quoteStatus:未上传,
events:{
eventDescription:event description ,
eventTypeName:事件类型
},
someReport:{
acceptResultsFlag:Y,
orderDate: 2017-06-14,
orderStatus:string
},
anotherReport:{
id:627311,
orderDate :2017-06-14
},
属性:[
{
appliedFlag:Y,
attributeDetail:{
name:name1,
value:value1
},
attributeName:attribute1
$,b

appliedFlag:N,
attributeDetail:{
name:name2,
value :value2
},
attributeName:attribute2
}
],
orderAttributes:[
{
appliedFlag:Y,
attributeDetail:{
name:name3,
value:value3
},
attributeName:orderAttribute1
},
{
appliedFlag:N,
attributeDetail:{
name:name4 ,
value:value4
},
attributeName:orderAttribute2
}
]
}
}' ''

def json = new JsonSlurper()。parse(input.bytes)

assert json.quote。属性[0] .attributeDetail.name =='name1'

json.quote.attributes [0] .attributeDetail.name = null

断言json.quote.attributes [ 0] .attributeDetail.name == null

我希望它有帮助。


I need to be able to find the key quote.orderAttributes[0].attributeDetail.name and set its value to null or any other value I want. I only need to do this for the first element in any list so selecting [0] is fine. I want to be able to use a path such as 'quote.orderAttributes.attributeDetail.name'. But given the amount of time I've spent so far, please advise of any better approaches.

Here is the Json:

{
  "source": "source",
  "orderId": null,
  "Version": null,
  "quote": {
    "globalTransactionId": "k2o4-6969-1fie-poef",
    "quoteStatus": "Not Uploaded",
    "events": {
      "eventDescription": "event description",
      "eventTypeName": "Event Type"
    },
    "someReport": {
      "acceptResultsFlag": "Y",
      "orderDate": "2017-06-14",
      "orderStatus": "string"
    },
    "anotherReport": {
      "id": 627311,
      "orderDate": "2017-06-14"
    },
    "attributes": [
      {
        "appliedFlag": "Y",
        "attributeDetail": {
          "name": "name1",
          "value": "value1"
        },
        "attributeName": "attribute1"
      },
      {
        "appliedFlag": "N",
        "attributeDetail": {
          "name": "name2",
          "value": "value2"
        },
        "attributeName": "attribute2"
      }
    ],
    "orderAttributes": [
      {
        "appliedFlag": "Y",
        "attributeDetail": {
          "name": "name3",
          "value": "value3"
        },
        "attributeName": "orderAttribute1"
      },
      {
        "appliedFlag": "N",
        "attributeDetail": {
          "name": "name4",
          "value": "value4"
        },
        "attributeName": "orderAttribute2"
      }
    ]
  }
}

I know the following works but requires that I know which object(s) is an ArrayList and specify its [0] indexed item:

def input = new File("src/test/resources/ShortExample.json")
def json = new JsonSlurper().parse(input)
def option1 = json['quote']["attributes"][0]["attributeDetail"]["name"]
println option1

//or this 
//where csvData.fullPath = quote.orderAttributes.attributeDetail.name

def (tkn1, tkn2, tkn3, tkn4) = csvData.fullPath.tokenize('.')
def option2 = json["$tkn1"]["$tkn2"][0]["$tkn3"]["$tkn4"]
println option2

I would like to be able to:

def input = new File("src/test/resources/ShortExample.json")
def json = new JsonSlurper().parse(input)
def changeValueTo = null
def (tkn1, tkn2, tkn3, tkn4) = csvData.fullPath.tokenize('.')
json["$tkn1"]["$tkn2"]["$tkn3"]["$tkn4"] = changeValueTo

I've tried to implement many of the examples on here using recursion, methods creating MapsOrCollections that identify what the object is and then search it for key or value, even trampoline examples.

If you could point me to a good article explaining serialization and deserialization it would be much appreciated too.

Thank you in advance.

解决方案

You can access and modify any nested field of JSON object directly, e.g.

json.quote.attributes[0].attributeDetail.name = null

This is possible, because new JsonSlurper().parse(input) returns a groovy.json.internal.LazyMap object. Groovy allows you to access and modify any Map entries using dot notation, e.g.

Map<String, Map<String, Integer>> map = [
    lorem: [ipsum: 1, dolor: 2, sit: 3]
]

println map.lorem.ipsum // Prints '1'
map.lorem.ipsum = 10
println map.lorem.ipsum // Prints '10'

You can apply same approach to your example, e.g.

import groovy.json.JsonSlurper

String input = '''{
  "source": "source",
  "orderId": null,
  "Version": null,
  "quote": {
    "globalTransactionId": "k2o4-6969-1fie-poef",
    "quoteStatus": "Not Uploaded",
    "events": {
      "eventDescription": "event description",
      "eventTypeName": "Event Type"
    },
    "someReport": {
      "acceptResultsFlag": "Y",
      "orderDate": "2017-06-14",
      "orderStatus": "string"
    },
    "anotherReport": {
      "id": 627311,
      "orderDate": "2017-06-14"
    },
    "attributes": [
      {
        "appliedFlag": "Y",
        "attributeDetail": {
          "name": "name1",
          "value": "value1"
        },
        "attributeName": "attribute1"
      },
      {
        "appliedFlag": "N",
        "attributeDetail": {
          "name": "name2",
          "value": "value2"
        },
        "attributeName": "attribute2"
      }
    ],
    "orderAttributes": [
      {
        "appliedFlag": "Y",
        "attributeDetail": {
          "name": "name3",
          "value": "value3"
        },
        "attributeName": "orderAttribute1"
      },
      {
        "appliedFlag": "N",
        "attributeDetail": {
          "name": "name4",
          "value": "value4"
        },
        "attributeName": "orderAttribute2"
      }
    ]
  }
}'''

def json = new JsonSlurper().parse(input.bytes)

assert json.quote.attributes[0].attributeDetail.name == 'name1'

json.quote.attributes[0].attributeDetail.name = null

assert json.quote.attributes[0].attributeDetail.name == null

I hope it helps.

这篇关于如何从使用Groovy嵌套在JSON中的ArrayList获取密钥并更改其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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