Grails - 导致JSONException的JSON绑定

时间:2014-06-04 14:48:19

标签: json grails groovy

我有以下控制器代码:

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

2 个答案:

答案 0 :(得分:1)

JSON转换器在Groovy Strings上窒息。我通过在.toString()打了一个"{'uuid':'$uuid'}".toString()来解决这个问题。

答案 1 :(得分:0)

试试这个

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()
}