Rest 如何在Grails2.3中的JSON呈现中排除集合的属性
我正在尝试设置rest Web服务(JSON),这就是我得到的:Rest 如何在Grails2.3中的JSON呈现中排除集合的属性,rest,grails,Rest,Grails,我正在尝试设置rest Web服务(JSON),这就是我得到的: {"name":"test","routines":[{"class":"Routine","id":1},{"class":"Routine","id":2}]} 这就是我想要的: {"name":"test","routines":[{"name": "routine-1"},{"name": "routine-2"}]} 我有以下领域: class Program { String name; sta
{"name":"test","routines":[{"class":"Routine","id":1},{"class":"Routine","id":2}]}
这就是我想要的:
{"name":"test","routines":[{"name": "routine-1"},{"name": "routine-2"}]}
我有以下领域:
class Program {
String name;
static hasMany = [routines: Routine]
}
class Routine {
String name
}
我有一个控制器:
class ProgramController extends RestfulController {
static responseFormats = ['json']
def show(Program program) {
respond program
}
}
我在resources.groovy中添加了这个
programRenderer(JsonRenderer, Program) {
excludes = ['class', 'id']
}
routineRenderer(JsonRenderer, Routine) {
excludes = ['class', 'id']
}
如何使用ProgramController的show方法/操作在json响应中包含例程的name属性?ObjectMarshaller方法在技术上是正确的。然而,代码编写起来很麻烦,而且将域的字段与封送拆收器同步是一个维护难题 本着Groovy的精神,我们非常乐意为每个REST域添加一点
out()
方法
Program.groovy
class Program {
String name
static hasMany = [routines: Routine]
def out() {
return [
name: name,
count: routines?.size(),
routines: routines?.collect { [name: it.name] }
]
}
}
import grails.converters.JSON
class ProgramController {
def show() {
def resource = Program.read(params.id)
render resource.out() as JSON
}
}
ProgramController.groovy
class Program {
String name
static hasMany = [routines: Routine]
def out() {
return [
name: name,
count: routines?.size(),
routines: routines?.collect { [name: it.name] }
]
}
}
import grails.converters.JSON
class ProgramController {
def show() {
def resource = Program.read(params.id)
render resource.out() as JSON
}
}
JSON响应
{
name: "test",
count: 2,
routines: [{ name: "routine-1" }, { name: "routine-2" }]
}
out()
方法可以轻松定制响应JSON,例如为例程数量添加count
。ObjectMarshaller方法在技术上是正确的。然而,代码编写起来很麻烦,而且将域的字段与封送拆收器同步是一个维护难题
本着Groovy的精神,我们非常乐意为每个REST域添加一点out()
方法
Program.groovy
class Program {
String name
static hasMany = [routines: Routine]
def out() {
return [
name: name,
count: routines?.size(),
routines: routines?.collect { [name: it.name] }
]
}
}
import grails.converters.JSON
class ProgramController {
def show() {
def resource = Program.read(params.id)
render resource.out() as JSON
}
}
ProgramController.groovy
class Program {
String name
static hasMany = [routines: Routine]
def out() {
return [
name: name,
count: routines?.size(),
routines: routines?.collect { [name: it.name] }
]
}
}
import grails.converters.JSON
class ProgramController {
def show() {
def resource = Program.read(params.id)
render resource.out() as JSON
}
}
JSON响应
{
name: "test",
count: 2,
routines: [{ name: "routine-1" }, { name: "routine-2" }]
}
out()
方法可以轻松定制响应JSON,例如为例程的数量添加count
。看一看。看一看。无论你选择什么,都会有维护问题,但这不依赖于任何grails魔法,因此+1无论你选择什么,都会有维护问题,但这并不依赖于任何圣杯魔法,所以+1