Forum Discussion

New2API's avatar
Frequent Contributor
5 years ago

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: [                           {                        ...
  • nmrao's avatar
    5 years ago

    Assuming that you are getting jdbc result as below xml





    def jdbcData = '''<Results>
        <ResultSet fetchSize="10">
            <Row rowNumber="1">
            <Row rowNumber="2">
            <Row rowNumber="3">
    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() 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() 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"