在grails中有很多关系的选择性深度渲染 [英] Selective deep rendering of hasMany relationships in grails
问题描述
对于以下域模型:
class Route {
字符串名称
static hasMany = [ checkPoints:CheckPoint]
static belongsTo = [someBigObject:SomeBigObject]
static mapping = {
checkPoints lazy:false
}
}
我需要将特定的 Route
返回为来自Web服务的JSON。我希望这个JSON包含所有的 checkPoints
,但没有其他的组合(即: someBigObject
)。
如果我这样做的话
$ $ p $ def route = Route.findById(id)
将路由呈现为JSON
我得到的是 checkPoints
,没有其他字段被提取:
{
class:com.example .Route,
id:1,
checkPoints:[
{
class:CheckPoint,
id:1
$,
{
class:CheckPoint,
id:2
},
{
class: CheckPoint,
id:4
},
{
class:CheckPoint,
id:3
}
],
someBigObject:{
class:SomeBigObject,
id:2
}
}
但是如果我这样做
pre $ code $ J $ B $ J将路由呈现为JSON
}
我得到了一切。我的意思是,几乎所有的数据库都通过各种关系获取。
有没有办法做到这一点,而无需手动创建jsonMaps?
您可以为选定的类注册自己的JSON编组器,并返回要呈现的属性。地图可以通过迭代类字段自动完成。 Marshaller ca在创建时注册在bootstrap或domain class中。
JSON.registerObjectMarshaller(Route){
返回[名称:it.name,checkPoints:it.checkPoints]
}
希望它有帮助
For the following domain model:
class Route {
String name
static hasMany = [checkPoints:CheckPoint]
static belongsTo = [someBigObject:SomeBigObject]
static mapping = {
checkPoints lazy: false
}
}
I need to return a specific Route
as a JSON from a web service. And I want this JSON to contain all the checkPoints
but no other compositions (i.e.:someBigObject
).
If I do
def route = Route.findById(id)
render route as JSON
all I got is the id's of the checkPoints
, no other field is fetched:
{
"class": "com.example.Route",
"id": 1,
"checkPoints": [
{
"class": "CheckPoint",
"id": 1
},
{
"class": "CheckPoint",
"id": 2
},
{
"class": "CheckPoint",
"id": 4
},
{
"class": "CheckPoint",
"id": 3
}
],
"someBigObject": {
"class": "SomeBigObject",
"id": 2
}
}
but if I do
JSON.use('deep') {
render route as JSON
}
I get everything. I mean, almost all the database is getting fetched through various relationships.
Is there way to do this without creating the jsonMaps manually?
You can register your own JSON marshaller for chosen classes and return properties which you want to render. Map can be done automatically by iteration over class fields. Marshaller ca be registered for example in bootstrap or in domain class during creation.
JSON.registerObjectMarshaller(Route) {
return [name:it.name, checkPoints:it.checkPoints]
}
There is nice article about it under: http://manbuildswebsite.com/2010/02/15/rendering-json-in-grails-part-3-customise-your-json-with-object-marshallers/
Hope it helps
这篇关于在grails中有很多关系的选择性深度渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!