我正在将 grails 插件从 1.3.4 升级到 grails 2.1.1。升级后,我现在有一个失败的集成测试,以前没有失败。它无法使用“as JSON”(grails.converters.JSON)。
@Test
public void testConvertCollectionOfEnvironmentSettingsToJSON() {
EnvironmentSetting setting = configurationService.getEnvironmentSetting('ENFORCE_SCHEMA_INSTANCE_RULE')
def jsonSetting = setting as JSON //exception thrown here
def s = jsonSetting as String
assertNotNull jsonSetting
}
异常和堆栈跟踪:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'com.company.ipsvc.configuration.domain.EnvironmentSettingAllRevs@48c12420' with class 'com.company.ipsvc.configuration.domain.EnvironmentSettingAllRevs' to class 'grails.converters.JSON'
at com.company.ipsvc.configuration.converter.json.basic.BasicEnvironmentSettingJSONIntegrationTests.testConvertCollectionOfEnvironmentSettingsToJSON(BasicEnvironmentSettingJSONIntegrationTests.groovy:28)
我能够成功使用 encodeAsJSON()。我也有与 XML 相同的问题。
最佳答案
我认为转换器(as JSON
语法)默认情况下仅适用于域对象和集合。
我相信,要转换任意对象,您应该使用 encodeAsJSON()
转换器。或者使用对象编码器,告诉转换器如何处理您的对象。
虽然文档对此不是很清楚..
参见:
- http://grails.org/Converters+Reference (底部的对象编码部分)
- http://grails.org/doc/latest/ref/Plug-ins/codecs.html
但我注意到 http://grails.org/doc/latest/api/grails/converters/JSON.html#JSON%28java.lang.Object%29说该对象转换 POGO。也许这意味着如果你有编码器?
我也确实找到了这个引用:
Notice that the ‘as’ operator is not overloaded for plain objects ...
Domain objects can use the ‘as’ operator to cast an object to JSON, the same as a collection. So unlike POGOs, where they must be massaged into a list or have encodeAsJSON explictly called ...
这似乎描述了这种情况。
关于json - 从 grails 1.3.4 升级到 grails 2.1.1 后无法使用 "as JSON",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12935881/