在Grails 2.3.1中从Controller渲染JSON响应

时间:2013-11-07 10:04:14

标签: json grails

在我的Grails-app中,我有两个域名Person和County

class Person {
     String firstName
     String lastName
     County county
     LocalDate dateOfBirth
     static hasMany = [episodes: Episode]
 }
 class County {
     String name
     // other stuff...
 }

当我尝试从我的控制器渲染我的人员列表时,我只获得郡{class:County,id:1}而不是郡名。我想要与我的Person相关的对象的属性。

def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    respond Person.list(params), model:[personInstanceCount: Person.count()]
}

我不想默认为深度转换器,然后我的belongsTo,并且hasMany关系似乎不起作用。

grails.converters.json.default.deep = true

我尝试过使用customRenderers并且失败了,Grails并不关心我在那里做的任何改变。

 personRenderer(JsonRenderer, Person) {
        excludes = ['class']
    }
    personsRenderer(JsonCollectionRenderer , Person){
        excludes = ['class']
    }
    countyRenderer(JsonRenderer, County) {
        excludes = ['class']
        includes = ['name']
    }
    countiesRenderer(JsonCollectionRenderer , County){
        excludes = ['class']
        includes = ['name']
    }

我试过CustomMarshallerRegistrar与上面相同的结果,没有任何反应,结果相同。 Se 8.1.6.2 http://grails.org/doc/latest/guide/webServices.html#objectMarshallerInterface

那么,我如何让我的Person-objects包含相关的County而不仅仅是Class和ID属性呢?

我在Windows上使用Grails 2.3.1和jdk 1.7

1 个答案:

答案 0 :(得分:1)

如果您有兴趣将其作为JSON回复,可以尝试以下方法:

在bootstrap中注册对象marshaller

JSON.registerObjectMarshaller(Person) {
    def person = [:]
    ['firstName', 'lastName', 'country', 'dateOfBirth'].each { name ->
        person = it[name]
    }
    return person
}

JSON.registerObjectMarshaller(Country) {
    def country = [:]
    ['name'].each { name ->
        country = it[name]
    }
    return country
}

然后作为您控制器的回复..

render text: [personList:Person.list(params), personInstanceCount: Person.count()] as JSON, contentType: 'application/json'