【问题标题】:Grails - JSON binding causing JSONExceptionGrails - JSON 绑定导致 JSONException
【发布时间】:2014-06-04 14:48:19
【问题描述】:

我有以下控制器代码:

def save(MyModel model) {
    model.save()
}

我正在使用以下方法对其进行测试:

//e.g. 2ff59e55-ee3d-4f66-8bfa-00f355f52c49
def uuid = UUID.randomUUID.toString()
controller.request.contentType = JSON_CONTENT_TYPE
controller.request.method = 'POST'
controller.request.json = "{'uuid': '$uuid', 'description': 'test object', 'count': 1}"
controller.save()

但是,每次我运行测试时,我都会得到,

org.apache.commons.lang.UnhandledException:
org.codehaus.groovy.grails.web.converters.exceptions.ConverterException:
org.codehaus.groovy.grails.web.json.JSONException: Value out of sequence: expected mode to be
OBJECT or ARRAY when writing '{'uuid': '2ff59e55-ee3d-4f66-8bfa-00f355f52c49', 'description': 'test object', 'count': 1}' but was INIT

【问题讨论】:

  • String uuid = UUID.randomUUID().toString()/{'uuid': "$uuid", 'description': 'test object'}/。使用斜杠字符串以便将" 用于 GString。
  • 糟糕。我更新了问题以更正uuid 部分;这只是一个错字。我用 /.../ 分隔的 GString 再次测试,但我仍然收到错误。

标签: json grails groovy


【解决方案1】:

JSON 转换器在 Groovy 字符串上阻塞。我已经解决了这个问题,方法是在末尾打一个.toString()"{'uuid':'$uuid'}".toString()

【讨论】:

    【解决方案2】:

    试试这个

    void "Test the save action correctly persists an instance"() {
        when:
        Integer originalCount = MyModel.count()
        String uuid = UUID.randomUUID().toString()
        controller.request.contentType = 'application/json'
        controller.request.method = 'POST'
        controller.request.json = ['uuid': uuid, 'description': 'test object'] as JSON
        controller.save()
    
        then:
        assert originalCount + 1 == MyModel.count()
    }
    

    【讨论】:

    • 这工作使用grails.converters.JSON。还有另一个 JSON 类型选项,但我没有再尝试了,因为我提到的那个在我第一次尝试时就起作用了。我对as 关键字很熟悉,但我很好奇为什么GString 不起作用,而这个...
    • 好的,虽然它不会产生错误,但它也没有设置属性。实际上,看起来 JSON 绑定根本不起作用,即使仅使用 {'description': 'test object'} 也不会设置 description 属性。
    • 我已经更新了我的答案。它正在过去。断言语句通过,这意味着我们在 MyModel 中多了一个条目。
    • 对于您的第一个评论问题,我没有理由这样做,但"{'uuid':" + uuid + ", 'description': 'test object'}" 也在工作..,.
    • 更新后的测试代码看起来与我所拥有的非常相似,并且它正在通过(即计数得到更新)。但是,控制器中的模型中没有任何数据。例如,model.description 为空。您正在使用哪个版本的 Grails 进行测试?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    相关资源
    最近更新 更多