在 grails 中渲染 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9639572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:13:12  来源:igfitidea点击:

Rendering JSON in grails

jsongrails

提问by Shenoy Tinny

I use the following code to render data in JSON format.

我使用以下代码以 JSON 格式呈现数据。

render(contentType:"text/json") {
    results = array {
        db.eachRow(query) { row ->
            def rs = row.toRowResult()
            def a = b(rs.name,c,d)
            aMap.put("A",a) 
            pair(aMap)
        }
    }
    if (results) {
        status = "OK"
    }
    else {
        status ="Nothing present"
    }
}

The above code generates JSON in the following format

上面的代码生成如下格式的JSON

{
    "results": [
        {"A":"value1"},
        {"A":"value2"},
        ...................
        {"A":"valuen"}
    ],
    "status":"OK"
}

As u see above, the data is rendered as an array of objects. Is there a way I can render the results data as an array of elements. Like

正如你在上面看到的,数据被呈现为一个对象数组。有没有办法可以将结果数据呈现为元素数组。喜欢

{
    "results": [
        "value1",
        "value2",
        ...................
        "valuen"
    ],
   "status":"OK"
}

回答by Esteban

The way the JSON object is being built is quite obscure. What I like doing to render JSON responses in grails is creating a map or list in groovy and then use the rendermethod just to convert it to JSON.

JSON 对象的构建方式非常模糊。我喜欢在 grails 中呈现 JSON 响应是在 groovy 中创建一个地图或列表,然后使用该render方法将其转换为 JSON。

Doing the transformation of the rowResult's inside the render method makes it quite confusing, I'd rather go for something like this

rowResult在 render 方法中进行 's的转换使它变得非常混乱,我宁愿去做这样的事情

def results = db.rows(query).collect { rowResult ->
    b(rowResult.name, c, d) 
}
render(contentType: 'text/json') {[
    'results': results,
    'status': results ? "OK" : "Nothing present"
]}

I think it's more readable, and even shorter. This snippet gets you the desired result: no objects inside the resultsarray, just strings.

我认为它更具可读性,甚至更短。此代码段为您提供了所需的结果:results数组中没有对象,只有字符串。

Note the use of rows, which returns a list of RowResult's, eliminating the need to get it from the ResultSet's. The list is used to collect the transformed value aby calling bon each row's name. Collecting the elements doesn't imply creating a map (like in the { "A":"value1"}JSON you were getting), just the same @will-buck achieved with the <<operator on a new, empty list.

请注意 的使用rows,它返回 RowResult 的列表,无需从 ResultSet 中获取它。该列表用于a通过调用b每一行的名称来收集转换后的值。收集元素并不意味着创建地图(就像在{ "A":"value1"}您获得的JSON 中一样),只是在<<新的空列表上使用运算符实现的 @will-buck 相同。

All we do with the render method is declaring the text/jsoncontent type and passing it a literal map containing the keys resultsand status, which you want to write to the response. The conditional operator is used to concisely determine the status. It could also be used like this, by means of the JSON converter @will-buck also mentioned:

我们对 render 方法所做的只是声明text/json内容类型,并将包含键results和的文字映射传递给它status,您希望将其写入响应。条件运算符用于简明地确定状态。它也可以这样使用,通过 JSON 转换器 @will-buck 也提到:

def responseData = [
    'results': results,
    'status': results ? "OK" : "Nothing present"
]
render responseData as JSON

回答by Will Buck

Only off by a little bit :) Just need to change

只有一点点:) 只需要改变

aMap.put("A", a)

to be a collection or list, rather than a map. so something like

是一个集合或列表,而不是一个地图。所以像

def aList = []
aList << a

Will get you what you want!

会得到你想要的!

As a sidenote, there is a JSON converter in grails that will do that string building for you. Look into it here

作为旁注,grails 中有一个 JSON 转换器,可以为您构建字符串。看看这里

回答by IgniteCoders

This should be enough to render a JSON from controller:

这应该足以从控制器呈现 JSON:

render results as grails.converters.JSON