我正在尝试将 JSON 数据发送到 Controller ,但 Controller 将其打印为 null。

以下是我的 Controller 代码的内容:

@Transactional 
def save(User user) {  
 
    println "${request.JSON}" 
    println "${request.JSON.owner}" 
    println request.format 
    user = new User(request.JSON) 
 
    if (user == null) { 
        transactionStatus.setRollbackOnly() 
        render status: NOT_FOUND 
        return 
    } 
 
    if (user.hasErrors()) { 
        transactionStatus.setRollbackOnly() 
        respond user.errors, view:'create' 
        return 
    } 
 
    user.save flush:true 
 
    respond user, [status: CREATED, view:"show"] 
} 

我已经尝试了此链接 Grails send request as JSON and parse it in controller 上给出的所有内容

网址映射:
 post "/user/"(controller: "user",parseRequest:true, action:"save") 

当我尝试这个时:
curl --data '{"owner":"new owner"}' --header "Content-Type: application/json" http://localhost:8080/user/ 

我得到的输出为:
{"message":"Property [owner] of class [class com.sample.User] cannot be null","path":"/user/index","_links":{"self":{"href":"http://localhost:8080/user/index"}} 

这是 Controller 的输出:
[:] 
null 
json 

我使用 rest-api 配置文件创建了应用程序,

Controller 接受“post”操作的“text/html”类型,但不接受 JSON
我可以使用 JSON 作为内容类型更新现有对象。

我的域类有三个字段
String owner 
String category 
Boolean deleted = false 

我正在使用 postman 发送 JSON 请求。
{ 
    "owner":"some user", 
    "category":"rule01" 
 } 

我究竟做错了什么?

请您参考如下方法:

[已编辑]

好的,我们一点一点去;在浏览器中尝试此 URL

http://localhost:8080/user/save?owner=the+beautiful&category=homo+sapiens 

使用下面的代码,
@Transactional 
def save() {      
    println params.owner 
    println params.category 
 
    render (params as JSON) 
} 

并在此处发布,无论您在浏览器中收到什么。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!