Guys need groovy help to build a json map
I am getting few values from a DB. I need to create json map from these values. I tried several things but not successful.
desired output: [
{
"roleId": "1",
"nameId": "123",
"addrId": "1234"
},
{
"roleId": "5",
"nameId": "456",
"addrId": "345"
},
{
"roleId": "7",
"nameId": "2356",
"addrId": "6756"
}
]
My DB output looks like this:
roleId nameId addrId
row1 1 123 1234
row2 5 456 345
row3 7 2356 6756
Below was my approach:
DB out put was assigned to a varibale called list.
import com.eviware.soapui.support.GroovyUtils import groovy.sql.Sql import groovy.json.* import groovy.json.JsonSlurper import groovy.json.JsonBuilder def jsonMap = new JsonSlurper().parseText '{"roleId":"", "nameId":"", "addrId": ""}' def jsonPayload def roleId def nameId def addrId //way to get data from DB //## Read SQL from a File to get data ##// //def getData = SQLPath+"getData.sql" //def Query = new File(getData).text //def list = sqlsvrConn.rows(Query) //list = DB outPUT list.each{ roleId = it.roleId nameId = it.nameId addrId = it.addrId jsonMap.roleId = roleId jsonMap.nameId = nameId jsonMap.addrId = addrId jsonPayload += jsonMap }
I was always getting last row added to jsonPayload.. any help is really appreciated.
Thanks in advance.
Assuming that you are getting jdbc result as below xml
def jdbcData = '''<Results> <ResultSet fetchSize="10"> <Row rowNumber="1"> <ROLEID>1</ROLEID> <NAMEID>123</NAMEID> <ADDRESSID>1234</ADDRESSID> </Row> <Row rowNumber="2"> <ROLEID>5</ROLEID> <NAMEID>456</NAMEID> <ADDRESSID>345</ADDRESSID> </Row> <Row rowNumber="3"> <ROLEID>7</ROLEID> <NAMEID>2356</NAMEID> <ADDRESSID>6756</ADDRESSID> </Row> </ResultSet> </Results>''' def jsonString = new groovy.json.JsonBuilder(new XmlSlurper().parseText(jdbcData).ResultSet.Row.collect { [ roleId: it.ROLEID.text(), nameId: it.NAMEID.text(), addrId: it.ADDRESSID.text() ] }).toPrettyString() log.info jsonString
In case if you have the list, you can use below:
def list = [[roleId:"1", nameId:"123", addrId:"1234"], [roleId:"5", nameId:"456", addrId:"345"], [roleId:"7", nameId:"2356", addrId:"6756"]] def jsonString = new groovy.json.JsonBuilder(list).toPrettyString() log.info jsonString
Either case, output will be:like as it is mentioned in the queston.
[ { "roleId": "1", "nameId": "123", "addrId": "1234" }, { "roleId": "5", "nameId": "456", "addrId": "345" }, { "roleId": "7", "nameId": "2356", "addrId": "6756" } ]