Grails - 将原始json分成对象

时间:2016-04-07 09:01:02

标签: json rest grails

我正在尝试从网址接收json,然后在我的页面上的g:select中显示它,并且一切似乎都正常工作,除了每个对象都显示为原始json(例如{id=1, regionCode=EC, regionName=EasternCape}而不是带有' id',' name'等的正确对象。这是我试图分裂的json:

[{"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}]

这是我用来接收上述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
    }
}

}

这是我的控制器将json放在gsp页面上的方式:

class MainController {

def getRegionService

    def index() {

        def regions = getRegionService.getRegion()

        [regions: regions]

    }
}

这里是显示选择的html片段:

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

2 个答案:

答案 0 :(得分:0)

我明白了。问题出在我的HTML中。选择应该是这样的:

<g:select name="setRegion" from="${regions}" optionValue="regionName" optionKey="regionCode"/>

答案 1 :(得分:0)

考虑三年后的情况,我会采取另一种方法。我还没有测试过任何东西,我只是在这里添加了它,以防其他任何人遇到同样的情况:

<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>

看到没有其他人试图回答这个问题,我想我得给自己一个“可接受的答案” xD