Deepak
Deepak

Reputation: 61

Grails - Error in generating custom JSON in controller

I am trying to create a custom json output in the controller using the following code but am getting an error "Unexpected token <" in the chrome rest client. The same code works for xml.

def customJSON = {

    def a = Student.list().get(0)

    render(contentType:"application/json"){

        student(){ name(a.firstName) }
    }

}

def customXml = {

    def a = Student.list().get(0)

    render(contentType:"text/xml"){

        student(){ name(a.firstName) }
    }

}

Upvotes: 0

Views: 474

Answers (1)

Dror Bereznitsky
Dror Bereznitsky

Reputation: 20376

Your code causes the following exception:

Message: Array elements must be defined with the "element" method call eg: element(value)
    Line | Method
->>   98 | invokeMethod      in grails.web.JSONBuilder

The problem is that grails send an HTML response with the content of the exception but with 'application/json' as the content type. So the client thinks it is an invalid JSON reponse.

The following code should work:

def a = Student.list().get(0)

render(contentType:"application/json"){
            student(name : a.firstName)
        }

Upvotes: 1

Related Questions