json - 从 grails 1.3.4 升级到 grails 2.1.1 后无法使用 "as JSON"

标签 json grails-2.0

我正在将 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/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 ...

http://manbuildswebsite.com/2010/02/08/rendering-json-in-grails-part-2-plain-old-groovy-objects-and-domain-objects/

这似乎描述了这种情况。

关于json - 从 grails 1.3.4 升级到 grails 2.1.1 后无法使用 "as JSON",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12935881/

相关文章:

hibernate - Grails 2.1:如何使用 “schema-export export”?

Grails 'java.lang.instrument ASSERTION FAILED' 错误

grails - 如何在Grails中使用PIN码而不是用户名和密码登录

caching - Grails 2.4.5在内存中缓存静态资源

grails - 如何将值附加到grails中的url

javascript - AngularJS:表单提交不返回 JSON 中的值

java - 将一维 JSON 数组解析为普通数组

javascript - 如何使用 jQuery 将 2 个 td 合并到一个 td 中?

javascript - 将带有 AJAX 的 JSON 发送到 Flask 语法错误

javascript - 无法让查询在 Angular 中工作