Json Grails获取子域对象

Json Grails获取子域对象,json,grails,grails-domain-class,Json,Grails,Grails Domain Class,我有两个域类,一个是父类,另一个是子类,它们之间有很多关系。父类有许多子类,子类属于父类。 这是一个编码示例 class Parent{ String name static hasMany = [childs:Child] static constraints = { } } class Child{ String name static belongsTo = [parent:Parent] static constraints={} }

我有两个域类,一个是父类,另一个是子类,它们之间有很多关系。父类有许多子类,子类属于父类。 这是一个编码示例

class Parent{
   String name
    static hasMany = [childs:Child] 
    static constraints = {
   }
}


class Child{
   String name
   static belongsTo = [parent:Parent]
   static constraints={}
}
问题是,一旦我获得父对象,与父类关联的子对象也会被获取。但是,当我将对象转换为JSON时,我无法完全看到子对象,只能看到子对象的ID。我想查看子对象的所有列,而不是仅查看Id

转换的JSON响应:

[{"class":"project.Parent","id":1,
  "name":"name1","childs":[{"class":"Child","id":1},{"class":"Review","id":2}]}]
但我想要包含子对象名称的响应,如下所示

[{"class":"project.Parent","id":1,"name":"name1",
  "childs":[{"class":"Child","id":1,"name":"childname1"},
            {"class":"Review","id":2,"name":"childname2"}
           ]
}]
非常感谢您的帮助。
提前感谢。

问题在于使用默认的JSON转换器。以下是您的选择:

 1. Default  -  all fields, shallow associations
    a. render blah as JSON

 2. Global deep converter - change all JSON converters to use deep association traversal
    a. grails.converters.json.default.deep = true

 3. Named config marshaller using provided or custom converters
    a. JSON.createNamedConfig('deep'){
        it.registerObjectMarshaller( new DeepDomainClassMarshaller(...) )
    }
    b. JSON.use('deep'){
        render blah as JSON
    }

 4. Custom Class specific closure marshaller 
    a. JSON.registerObjectMarshaller(MyClass){ return map of properties}
    b. render myClassInstance as JSON

 5. Custom controller based closure to generate a map of properties
    a. convert(object){
        return map of properties
    }
    b. render convert(blah) as JSON
您当前正在使用默认选项1


最简单的方法是使用选项2设置全局深度转换器,但请注意这会影响应用程序中的所有域类。这意味着,如果您有一个以顶级对象为顶点的大型关联树,并且您尝试转换这些顶级对象的列表,则深度转换器将执行所有查询,依次获取所有关联对象及其关联对象。-您可以一次性加载整个数据库(请小心。

用户dbrin是正确的,但还有一个选项。您还可以使用Grails GSON插件:


该插件在处理json数据时添加了更多功能

最新的grails自动进行深度转换,但您可能是延迟加载的受害者

访问时未加载子项,因此JSON转换器无法将其转换为JSON。 解决办法是把这个


静态映射={childs lazy:false}

建议的解决方案正在工作,但是我在引用“grailsApplication”时遇到了一些问题。事实证明,你可以像其他服务一样接受它。我将以下代码放入

BootStrap.groovy

文件。另外,类DeepDomainClassMarshaller可以很好地处理双向循环引用,但是要注意,JSON负载在深度延迟之后并不是很大

package aisnhwr

import grails.converters.JSON
import grails.core.GrailsApplication
import org.grails.web.converters.marshaller.json.DeepDomainClassMarshaller

class BootStrap {

    GrailsApplication grailsApplication

    def init = { servletContext ->
        JSON.createNamedConfig('deep'){
            it.registerObjectMarshaller( new DeepDomainClassMarshaller(false, grailsApplication) )
        }
    }
    def destroy = {
    }
}

嘿,谢谢,我使用了第三种方法JSON。使用('deap'){render Parent as JSON}它就像我期望的那样工作。我也遇到了类似的问题,我的方法第一次工作,然后总是父类属性。我使用的是JSON.use('deep'),那么Grails3.3.8中的也不起作用。child被正确地加载到域实例中,但一旦在JSON中转换,它们仍然只显示id