我正在尝试将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
我正在使用邮递员发送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)
}
并在此处发布,无论您在浏览器中收到什么。
关于json - 无法将JSON数据获取到 Controller 中, Controller 将JSON请求显示为null;,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40191312/