json - 在 Grails 2.3.1 中从 Controller 渲染 JSON 响应

标签 json grails

在我的 Grails 应用程序中,我有两个域 Person 和 County

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

当试图从我的 Controller 呈现我的人员列表时,我只得到 County { class: County, id: 1 } 而不是 County 的名称。我想要与我的人相关的对象的属性。
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,您可以尝试以下操作:

在 Bootstrap 中注册对象编码器

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
}

然后作为 Controller 的响应..
render text: [personList:Person.list(params), personInstanceCount: Person.count()] as JSON, contentType: 'application/json'

关于json - 在 Grails 2.3.1 中从 Controller 渲染 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19832984/

相关文章:

php - 如何通过 PHP 使用 Azure 开放数据

java - 在 JAVA 中读取一个 JSON 数组

java - 用于创建高负载 Web 服务的语言和框架?

grails - 如何使用 spock 在 where block 上测试索引?

java - 解码json android

java - 没有换行字符的 JSON Java

javascript - 将 PHP 数组传递给 js 变量

grails - Grails 中的错误 : Save the transient instance before flushing

Grails 表单错误处理 : Binding 1:1 object mappings

grails - 由SessionFixationProtectionStrategy引起的 session 无效