使用grails 2.4.0和RESTful控制器(JSON)并寻找指导。
我有非常简单的域名(来自样本):
class Project {
String name
String description
static belongsTo = [owner : EndUser]
static constraints = {
name(blank: false, unique: true)
description()
}
}
class EndUser {
String userName
String fullName
String toString() {
"${fullName}"
}
static hasMany = [projects : Project]
static constraints = {
fullName()
userName(unique: true)
}
}
在ProjectController中,除了JSON之外,我还保留了html进行测试。
class ProjectController extends RestfulController {
static responseFormats = ['html', 'json', 'xml']
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond Project.list(params), model:[projectInstanceCount: Project.count()]
}
def show(Project projectInstance) {
respond projectInstance
}
def listWithFullName(){
def a = Project.list(params)
a.owner.fullName
respond a
}
}
如果转到html页面:/ project / show / 1,我会得到包含详细信息的html页面:
HTML page:
Name: prj1
Description: prj desc
Owner: full name1
到目前为止一切顺利,如果我和json(/project/show/1.json)一样,我得到:
{
class: "testapp.Project"
id: 1
description: "prj desc"
name: "prj1"
owner: {
class: "testapp.EndUser"
id: 2
}
}
如你所见"所有者" JSON中的字段我得到" id"。如何在JSON中获取所有者的全名。我以为我可以做一些事情,比如我在控制器中尝试的方法:listWithFullName()但是没有用。有什么指针吗?感谢。