Forum Discussion

New2API's avatar
New2API
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">
                <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"
        }
    ]