In groovy how can I create ouput json in the below two structure by using the below input. I have done in java but I'm not getting how can I do in groovy.
INPUT:
{
"name": "app",
"test2": [
{
"status": [
{
"id": 1,
"pole": [
{
"Color": "RED",
"Status": 0
},
{
"Color": "AMBER",
"Status": 0
},
{
"Color": "GREEN",
"Status": 0
}
]
},
{
"id": 2,
"pole": [
{
"Color": "RED",
"Status": 0
},
{
"Color": "AMBER",
"Status": 0
},
{
"Color": "GREEN",
"Status": 0
}
]
}
]
},
{
"status": [
{
"id": 1,
"pole": [
{
"Color": "RED",
"Status": 0
},
{
"Color": "AMBER",
"Status": 0
},
{
"Color": "GREEN",
"Status": 0
}
]
},
{
"id": 2,
"pole": [
{
"Color": "RED",
"Status": 0
},
{
"Color": "AMBER",
"Status": 0
},
{
"Color": "GREEN",
"Status": 0
}
]
}
]
}
]
}
Ouput1: One to many output should be produced where by iterating many output of the below structure need to be produced.Like the below output it should produce 12 JSON Object.
{
"OUTPUT": {
"STATUS": {
"id": "1",
"color": "RED"
}
}
}
Output2:
{
"OUTPUT": {
"STATUS": [{
"id": "1",
"color": "RED"
},{
"id": "1",
"color": "AMBER"
}
.
.
{
"id": "2",
"color": "RED"
}
]
}
}
As I'm new to groovy I'm not getting clearly how I can do this.
Below is the code which I have tried so, far.
import groovy.json.*;
def data='''{"name": "app","test2": [{"status": [{"id": 1,"pole": [{"Color": "RED","Status": 0},{"Color": "AMBER","Status": 0},{"Color": "GREEN","Status": 0}]},{"id": 2,"pole": [{"Color": "RED","Status": 0},{"Color": "AMBER","Status": 0},{"Color": "GREEN","Status": 0}]}]},{"status": [{"id": 1,"pole": [{"Color": "RED","Status": 0},{"Color": "AMBER","Status": 0},{"Color": "GREEN","Status": 0}]},{"id": 2,"pole": [{"Color": "RED","Status": 0},{"Color": "AMBER","Status": 0},{"Color": "GREEN","Status": 0}]}]}]}'''
def data1 = new JsonSlurper().parseText( data );
def a=[:]
def OU=[:]
def status=[]
a.OUTPUT=OU
OU.STATUS=status
for(def i=0;i<data1.test2.size();i++){
for(def j=0;j<data1.test2[i].status.size();j++){
def b=[:]
b.id=data1.test2[i].status[j].id
for(def k=0;k<data1.test2[i].status[j].pole.size();k++){
b.color=data1.test2[i].status[j].pole[k].Color
status<<b
}
}
}
String finalJson = JsonOutput.toJson a;
println finalJson
Is this the correct way forming json(using map) as I found apart from JSONBuilder, Map is also another way for creating JSON. Earlier I was using org.json for creating dynamic json normlization script so, if the above method which I used is correct then I can proceed with generating dynamic data normalization from JSON-JSON with the groovy script from java code.