Rahul Ram
Rahul Ram

Reputation: 21

not able to get json data into controller, controller shows JSON request as null;

I am trying to send JSON data into the controller, but controller prints it as null.

Below is the content of my controller code:

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

I have tried everything given at this link Grails send request as JSON and parse it in controller

URL mappings:

 post "/user/"(controller: "user",parseRequest:true, action:"save")

When I try this:

curl --data '{"owner":"new owner"}' --header "Content-Type: application/json" http://localhost:8080/user/

I get output as:

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

This is the output from controller:

[:]
null
json

I created the app using rest-api profile,

Controller accepts "text/html" type for "POST" operation but not JSON and I can update an existing object with JSON as content type.

My domain class has three fields

String owner
String category
Boolean deleted = false

I am using postman to send JSON requests.

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

What am I doing wrong?

Upvotes: 2

Views: 982

Answers (2)

Teejay
Teejay

Reputation: 51

I got the same issue and after trying some guesses :) here is how I managed to resolve it.

Json Request:

json request

My controller:

 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]
 }

For curl:

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

I tried avoiding jsonSlurper in my controller but I just could not get my values without it.

Hope it helps.

Upvotes: 0

Adeel Ansari
Adeel Ansari

Reputation: 39907

[Edited]

Okay, we go little by little; try this URL in your browser

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

with this code below,

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

    render (params as JSON)
}

and post here, whatever you receive in the browser.

Upvotes: 0

Related Questions