如何使用Groovy基于键值将信息从一个JSON丰富到另一个JSON中?如下所示,基于MainJson中的键"Id"的值,我需要在SecondJson中查找"id"。当找到匹配时,我需要从SecondJson中获取对象"name"并将其附加到MainJson
主要内容:
[
{
"webshop": [
{
"id": "1168190",
"type": "segment",
"values": [
{
"id": "1168191",
"type": "application",
"values": [
{
"id": "1168192",
"type": "productRange"
},
{
"id": "1168193",
"type": "productRange"
}
]
},
{
"id": "1168194",
"type": "application",
"values": [
{
"id": "1168195",
"type": "productRange"
},
{
"id": "1168196",
"type": "productRange"
}
]
}
]
}
]
}]
第二个儿子:
{
"ProductCategorization": [
{
"code": "1168190",
"name": [
{
"en": "Irrigation"
},
{
"es": "Riego"
}
]
},
{
"code": "1168191",
"name": [
{
"ES": "Kenadrain"
},
{
"EN": "Kenadrain"
}
]
},
{
"code": "1168192",
"name": [
{
"ES": "Fluxol"
},
{
"EN": "Fluxol"
}
]
},
{
"code": "1168193",
"name": [
{
"EN": "PP System Jimten"
},
{
"ES": "PP System Jimten"
}
]
}]}
要求输出:
[
{
"webshop": [
{
"id": "1168190",
"type": "segment",
"name": [
{
"en": "Irrigation"
},
{
"es": "Riego"
} ],
"values": [
{
"id": "1168191",
"type": "application",
"name": [
{
"ES": "Kenadrain"
},
{
"EN": "Kenadrain"
} ]
"values": [
{
"id": "1168192",
"type": "productRange",
"name": [
{
"ES": "Fluxol"
},
{
"EN": "Fluxol"
}
],
我尝试了下面的代码,但是,JSON只是附加到第一个JSON,而不是查找匹配项并附加相关对象
def json1 = message.getBody(String);
def map = message.getHeaders();
def json2 = map.get("category");
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.each{ it.webshop?.each{ node -> node.name = json2Obj.ProductCategorization.findAll{item -> item.code == it.id }.name[0]
it.values?.each{ node1 -> node1.name = json2Obj.ProductCategorization.findAll{item1 -> item1.code == it.id }.name[0]
it.values?.each{ node2 -> node2.name = json2Obj.ProductCategorization.findAll{item2 -> item2.code == it.id }.name[0]
it.values?.each{ node3 -> node3.name = json2Obj.ProductCategorization.findAll{item3 -> item3.code == it.id }.name[0] } } } } }
def out= JsonOutput.toJson(json1Obj)
message.setBody(out);
return message;
1条答案
按热度按时间vdzxcuhz1#
使用递归函数遍历
main
以查找id及其在second
JSON中的对应项,代码如下所示:印刷品