Grails无法将JSON数组转换为HashMap

时间:2014-10-17 17:10:40

标签: json grails groovy hashmap

我有以下JSON(在Groovy中存储为String):

{
    "isFizz": "true",
    "buzzProperties": [
        {
            "foo": "bar"
        },
        {
            "widget": 35
        }
    ],
    "name": "dummy1"
}

在我的Grails控制器中,我有以下方法将此JSON作为HTTP请求处理,并尝试将JSON读入Groovy变量:

Stuff register() {  
    def jsonObject = request.JSON
    Stuff stuff = new Stuff()
    stuff.isFizz                    = jsonObject.isFizz
    stuff.buzzProperties            = jsonObject.buzzProperties             // stuff.buzzProperties is a HashMap
    stuff.name                      = jsonObject.name

    stuff
}

当控制器方法执行时(当它收到请求时),我得到以下异常:

Cannot cast object '[{"foo":"bar"},{"widget":35}]' with class 'org.codehaus.groovy.grails.web.json.JSONArray' to class 'java.util.Map' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Map(org.codehaus.groovy.grails.web.json.JSONObject, org.codehaus.groovy.grails.web.json.JSONObject). Stacktrace follows:
    org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[{"foo":"bar"},{"widget":35}]' with class 'org.codehaus.groovy.grails.web.json.JSONArray' to class 'java.util.Map' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Map(org.codehaus.groovy.grails.web.json.JSONObject, org.codehaus.groovy.grails.web.json.JSONObject)

我针对JSON lint检查了JSON,它是完全有效的JSON。这里发生了什么?

1 个答案:

答案 0 :(得分:3)

请注意buzzProperties不是Map List {}[] vs buzzProperties)。这就是铸造无法进行的原因。将List类型更改为Map或发送有效的{ "isFizz": "true", "buzzProperties": { "foo": "bar", "widget": 35 }, "name": "dummy1" }

修改

您发送的json字符串应按以下方式定义:

{{1}}