默认情况下,Grails 使用 XML 呈现 List<list>
元素标签位于其根部。同样,它渲染 Map<map>
。我想控制根元素的名称。
如果我返回 User 的 ArrayList,那么我想看到:
<users>
<user>...</user>
<user>...</user>
</users>
我怎样才能实现上述目标?以下是要求:
- 可以轻松地将这种序列化应用于 50 多个域类
- 从开发人员那里抽象出来,因此在渲染域对象期间不需要显式编码(即,当
render()
or respond()
被调用时,仍然传入 ArrayList,没有像这样的显式转换/转换as MyNewType
)
- 能够处理空列表的边缘情况(应该返回
<users/>
)
必备品:
我已经半成功地实现了上述目标,但我不知道如何解释空列表的情况。我实现了自己的 ObjectMarshaller,它呈现所有类型的对象List
。只要列表包含一个元素,我就可以检查该元素的类型并确定复数标记名称应该是什么(User => users)。但是,如果列表为空,并且由于 Java 泛型是通过擦除(除非 Groovy 中不同?),那么除了默认为类似的内容之外,我无法正确命名空列表<list/>
,这是不可接受的。
我已经经历过的一些资源:
- http://www.cacoethes.co.uk/blog/groovyandgrails/dry-json-and-xml-with-grails http://www.cacoethes.co.uk/blog/groovyandgrails/dry-json-and-xml-with-grails
- http://grails.1312388.n4.nabble.com/Custom-XML-Marshaller-change-the-root-element-name-td4649949.html http://grails.1312388.n4.nabble.com/Custom-XML-Marshaller-change-the-root-element-name-td4649949.html
- http://jwicz.wordpress.com/2011/07/11/grails-custom-xml-marshaller/ http://jwicz.wordpress.com/2011/07/11/grails-custom-xml-marshaller/
- http://mrhaki.blogspot.com/2013/11/grails-goodness-register-custom.html http://mrhaki.blogspot.com/2013/11/grails-goodness-register-custom.html
- http://manbuildswebsite.com/2010/02/15/rendering-json-in-grails-part-3-customise-your-json-with-object-marshallers/ http://manbuildswebsite.com/2010/02/15/rendering-json-in-grails-part-3-customise-your-json-with-object-marshallers/
实现此目的的一种方法是为 CollectionMarshaller 类编写一个子类并将其注册到我们的 Grails 应用程序中。例如,我们可以使用以下代码在 BootStrap.groovy 中注册自定义实现:
import org.codehaus.groovy.grails.web.converters.marshaller.xml.CollectionMarshaller
import grails.converters.XML
class BootStrap {
def init = { servletContext ->
// Register custom collection marshaller for List with User instances.
// The root element name is set to users.
XML.registerObjectMarshaller(new CollectionMarshaller() {
@Override
public boolean supports(Object object) {
object instanceof List<User>
}
@Override
String getElementName(final Object o) {
'users'
}
})
}
}
为了使这项工作适用于更多域类,我们可以获取 BootStrap.groovy 中所有域类的引用,并循环遍历它们以配置自定义 CollectionMarshaller 实例。
对于地图,您可以扩展 MapMarshaller
也描述于http://mrhaki.blogspot.com/2014/02/grails-goodness-customize-root-element.html http://mrhaki.blogspot.com/2014/02/grails-goodness-customize-root-element.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)