Roman
Roman

Reputation: 66216

How to obtain JSON (or XML) response from Grails?

I have 1 domain class, 1 controller, 1 URL mapping (see below). I want to send request, and receive JSON response.

But currently my request is correctly mapped to the correspondent controller method, the method is successfully executed, and then I get an error with message that jsp-file not available.

How to explain Grails, that I don't need no jsp-files: I want to receive/parse JSON requests, and send JSON responses right from my controllers?

class Brand {

    String name
    String description
    String logoImageURL

    static constraints = {
        name(blank: false)
    }
}

---------------------------
class UrlMappings {
     static mappings = {
        "/brands"(controller: "brand", parseRequest: true, action: "list")
     }
}

---------------------------
import grails.converters.JSON

class BrandController {

    def list = {
        return Brand.list() as JSON
    }

    def show = {
        return Brand.get(params.id) as JSON
    }

    def save = {
        def brand = new Brand(name: params.name, description: params.description, logoImageURL: params.logoURL)
        if (brand.save()) {
            render brand as JSON
        } else {
            render brand.errors
        }
    }
}

============== Error message ===============
Request URL: http://localhost:8080/ShoesShop/brands

message /ShoesShop/WEB-INF/grails-app/views/brand/list.jsp

description The requested resource (/ShoesShop/WEB-INF/grails-app/views/brand/list.jsp) is not available.

Upvotes: 2

Views: 1550

Answers (1)

tim_yates
tim_yates

Reputation: 171164

It should work if you instead do:

def list = {
    render Brand.list() as JSON
}

Upvotes: 3

Related Questions