如何从Grails获取JSON(或XML)响应?

时间:2012-05-17 14:45:33

标签: rest grails

我有1个域类,1个控制器,1个URL映射(见下文)。我想发送请求,并收到JSON响应。

但是目前我的请求已正确映射到通信控制器方法,该方法已成功执行,然后我收到错误消息,指出jsp-file不可用。

如何解释Grails,我不需要没有jsp文件:我想接收/解析JSON请求,并直接从我的控制器发送JSON响应?

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.

1 个答案:

答案 0 :(得分:3)

如果您instead这样做,它应该有效:

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