【问题标题】:not able to get json data into controller, controller shows JSON request as null;无法将 json 数据输入控制器,控制器将 JSON 请求显示为空;
【发布时间】:2016-10-22 10:57:24
【问题描述】:

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

以下是我的控制器代码的内容:

@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"}}

这是控制器的输出:

[:]
null
json

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

控制器接受“text/html”类型进行“POST”操作,但不接受 JSON 我可以使用 JSON 作为内容类型更新现有对象。

我的域类有三个字段

String owner
String category
Boolean deleted = false

我正在使用邮递员发送 JSON 请求。

{
    "owner":"some user",
    "category":"rule01"
 }

我做错了什么?

【问题讨论】:

  • 哪个 grails 版本?
  • 我正在使用 grails 3.2.1
  • 发布您的params 的转储。

标签: json rest grails controller


【解决方案1】:

[已编辑]

好的,我们一点一点地去;在浏览器中试试这个网址

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

下面这段代码,

@Transactional
def save() {     
    println params.owner
    println params.category

    render (params as JSON)
}

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

【讨论】:

  • 试过这个.. 仍然是“null”
  • println params 的输出是什么?
  • 打印时输出“null”
  • 你的意思是没有params。但是在您发布的问题中,request.formatjson 的输出;不是吗?
  • 是的,我从 Postman 传递参数。我的 println params['owner']println params['category'] 为空
【解决方案2】:

我遇到了同样的问题,在尝试了一些猜测之后:)这是我设法解决的方法。

Json 请求:

我的控制器:

 def postentry (accountno){

 def fulldata = request.reader.text
 def ddd =  new JsonSlurper().parseText(fulldata)
 accountno = ddd.accountno[0].toString()
 println accountno
 transidd = ddd.transid[0].toString()
 transamtt = ddd.transamt[0].toString()
 transtype = ddd.transtype[0]
 }

对于卷曲:

 POST /transact HTTP/1.1
 Host: localhost:8080
 Content-Type: application/json
 Cache-Control: no-cache
 Postman-Token: aa898872-e448-bace-9f6d-143bdc0b03db

 [{
 "accountno": 000710023005,
 "transid": 16,
 "transamt": 20.25,
 "transtype": "withdrawal"
 }]

我尝试在控制器中避免使用 jsonSlurper,但没有它我无法获得我的值。

希望对你有帮助。

【讨论】:

  • 这是来自 grails 3.x.x
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多