【问题标题】:How to obtain JSON (or XML) response from Grails?如何从 Grails 获取 JSON(或 XML)响应?
【发布时间】:2012-05-25 03:55:36
【问题描述】:

我有 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.

【问题讨论】:

    标签: rest grails


    【解决方案1】:

    如果你 instead 这样做应该可以:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多