【发布时间】:2017-06-05 10:43:41
【问题描述】:
我刚刚开始使用 Grails 2.4.4,我正在尝试创建一个输出 JSON 的 REST api,但是在将对象呈现为 JSON 时我遇到了问题。下面列出的是域类、控制器和 objectmarshall。
领域类:
@Resource(uri='/users')
class User {
List contacts;
String name;
String password;
static hasMany=[contacts:Contact]
static constraints = {
}
static mapping = {
contacts lazy: false
}
}
控制器:
class UserController {
def index() {
//json
render User.getAll() as JSON
}
Boostrap 常规:
class BootStrap {
def init = { servletContext ->
JSON.registerObjectMarshaller(User) {
def output = [:]
output['id'] = it.id
output['name'] = it.name
output['contacts'] = it.contacts
return output;
}
JSON.registerObjectMarshaller(Contact) {
def output = [:]
output['id'] = it.id;
output['name'] =it.name;
output['phoneNumber'] = it.phoneNumber;
output['userId'] = it.user.id;
return output;
}
}
}
在我第一次运行我的应用程序后,它会返回 XML 而不是 JSON,但是如果我进行新的更改会生成热部署(例如,如果我添加评论),它将生成 JSON。
我错过了什么?
【问题讨论】: