我正在尝试设置一个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;
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方法/操作将例程的name属性包含在json响应中?
ObjectMarshaller方法是技术上正确的方法。然而,代码编写起来很麻烦,而且将域的字段与marshaller同步是一个维护难题。
本着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] }
]
}
}
ProgramController.groovy
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
。