【问题标题】:Grails rendering JSONGrails 渲染 JSON
【发布时间】: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。

我错过了什么?

【问题讨论】:

    标签: json grails groovy


    【解决方案1】:

    我发现创建您想要的地图并进行渲染要简单得多。

    def renderMe = [name: "Joe"]
    render renderMe as JSON
    

    【讨论】:

    • 真正解决我的问题的是删除@Resource 注释。看来注解和render as方法之间存在某种冲突
    【解决方案2】:

    尝试用render(contentType:"application/json")声明内容类型

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 2012-03-27
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2016-09-08
      • 1970-01-01
      相关资源
      最近更新 更多