Search code examples
jsonrestgrails

Grails - splitting raw json into an object


I am trying to receive json from a url and then display it in a g:select on my page and everything seems to work fine except that each object is displayed as raw json (e.g. {id=1, regionCode=EC, regionName=EasternCape} instead of proper objects with 'id', 'name', etc. Here's the json I'm trying to split:

[{"regionCode":"EC","regionName":"Eastern Cape","id":1},
{"regionCode":"FS","regionName":"Free State","id":2},
{"regionCode":"GA","regionName":"Gauteng","id":3},
{"regionCode":"KZN","regionName":"Kwa-Zulu Natal","id":4},
{"regionCode":"LI","regionName":"Limpopo","id":5},
{"regionCode":"MP","regionName":"Mpumalanga","id":6},
{"regionCode":"NW","regionName":"North West","id":8},
{"regionCode":"NC","regionName":"Northern Cape","id":7},
{"regionCode":"WC","regionName":"Western Cape","id":9}]

Here's the service I'm using to receive the above json:

class GetRegionService {

def getRegion(){

    try{
        //I'm not using the actual URL in this example
        def regionList = new JsonSlurper().parseText(new URL('http:url/regions/list/ZA/').text)
        return regionList
    }catch (all){
        all.printStackTrace()
        return false
    }
}

}

Here's how my controller that puts the json on the gsp page:

class MainController {

def getRegionService

    def index() {

        def regions = getRegionService.getRegion()

        [regions: regions]

    }
}

And here's the html snippet where the select is displayed:

<div class="jumbotron">
    <label for="setRegion" style="margin: 0 10px 0 50px">Region: </label>
    <g:select name="setRegion" from="${regions}"/>
</div

Solution

  • Looking at this from three years later, I'd take another approach. I haven't tested this or anything, I'm just adding this here in case anyone else ever finds themselves in the same situation:

    <html>
        <head></head>
        <body>
            <!-- Stuff here -->
    
            <select id="setRegion" name="setRegion"></select>
    
            <!-- More stuff here -->
    
            <script>
                $(document).ready(function() {
                    $('#setRegion').html('').append(
                        $('<option/>').text('-- Select Region')
                    );
    
                    JSON.parse('${regions}').forEach(function(region, i) {
                        $('#setRegion').append(
                            $('<option/>').attr({ value:region.regionCode }).text(region.regionName)
                        );
                    });
                });
            </script>
        </body>
    </html>
    

    And seeing as nobody else has tried to answer this question, I guess I'll have to give myself the "accepted answer" xD