1

I have a simple action such as this:

def showSomething() {
   render Color.get(params.id) as JSON
}

This will render all the properties in the Color class as JSON. However, what if I only want to render two properties, say, colorName and shade?

4

3 回答 3

2

如果您想在每次渲染对象时渲染相同的属性,Gjordis 有正确的选择。但是,您可以简单地这样做:

Color color = Color.get(params.id)
render ([colorName: color.colorName, shade: color.shade] as JSON)
于 2013-05-15T13:15:44.320 回答
2

这很简单:

def relevantProperties = ["colorName","shade"]
def color = Color.get(params.id)
def reply = relevantProperties.collectEntries { property ->
    [property, color[property]]
}

render reply as JSON

你在那里:-)

于 2013-05-15T12:43:45.177 回答
1
import grails.converters.JSON
class BootStrap {
    def init = {servletContext ->
        JSON.registerObjectMarshaller(Color) {
            def returnArray = [:]
            returnArray['shade'] = it.shade
            returnArray['colorName'] = it.colorName
            return returnArray
    }

}

有人可以纠正我,我没有使用过grails。但是覆盖转换中调用的函数是关键。

于 2013-05-15T12:43:55.167 回答