【问题标题】:Render JSON-response from Controller in Grails 2.3.1在 Grails 2.3.1 中从 Controller 渲染 JSON 响应
【发布时间】:2013-11-07 10:04:14
【问题描述】:

在我的 Grails 应用程序中,我有两个域 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 } 而不是县的名称。我想要与我的人相关的对象的属性。

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 与上面相同的结果,没有任何反应,结果相同。硒 8.1.6.2 http://grails.org/doc/latest/guide/webServices.html#objectMarshallerInterface

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

我在 Windows 上使用带有 jdk 1.7 的 Grails 2.3.1

【问题讨论】:

    标签: json grails


    【解决方案1】:

    如果您有兴趣将其响应为 JSON,您可以尝试以下操作:

    在引导程序中注册对象编组器

    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'
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2017-06-05
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2017-08-29
    • 2021-02-17
    相关资源
    最近更新 更多