[英]How do I render plain object as JSON, XML in Grails?
I have a controller ( RestfulController
) code similar to the following: 我有一个类似于以下内容的控制器( RestfulController
)代码:
def doSomethingAwesome() {
Domain domainObject = prepareDomainObject()
//do something on the domain object
Model model = new Model(name: domainObject.name, description: domainObject.description)
respond model
}
As can be seen, I'm trying to respond with data wrapped inside a Model
object. 可以看出,我试图用包装在Model
对象中的数据进行响应。 However, Model
class is not a domain class; 但是, Model
类不是域类;它不是域类。 it's just a plain Groovy class. 这只是一个普通的Groovy类。 When I try to test this code in isolation, I get it to pass, but when I test it with all the other tests, I get GroovyCastException
saying the object cannot be cast to JSON. 当我尝试GroovyCastException
测试此代码时,我会通过它,但是当我与所有其他测试一起对其进行测试时,我得到了GroovyCastException
该对象无法转换为JSON。
Some of the articles that came up of my searches suggest I put the model object inside a map then have that map get rendered. 我搜索中出现的一些文章建议我将模型对象放在地图中,然后渲染该地图。 Something like: 就像是:
render ['model': model] as JSON
However, this isn't how I'd like the response message to be. 但是,这不是我想要的响应消息。 In addition, the XML message would look very different. 此外,XML消息看起来会非常不同。
The Grails 2.4.3 demo project at https://github.com/jeffbrown/pogorespond demonstrates passing a POGO (not a domain class) to the respond
method. 在Grails的2.4.3演示项目https://github.com/jeffbrown/pogorespond演示传递POGO(不是域类)的respond
方法。 https://github.com/jeffbrown/pogorespond/blob/1646c64fe2b37856fc87b64ae1cf5a6c4fd44cb1/grails-app/controllers/demo/DemoController.groovy contains the following: https://github.com/jeffbrown/pogorespond/blob/1646c64fe2b37856fc87b64ae1cf5a6c4fd44cb1/grails-app/controllers/demo/DemoController.groovy包含以下内容:
package demo
class DemoController {
static responseFormats = ['json']
def index() {
def m = new Model(name: 'Some Name', description: 'Some Description')
respond m
}
}
class Model {
String name
String description
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.