【问题标题】:Grails cannot cast JSON array to HashMapGrails 无法将 JSON 数组转换为 HashMap
【发布时间】:2014-12-13 08:03:46
【问题描述】:

我有以下 JSON(在 Groovy 中存储为字符串):

{
    "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。这是怎么回事?

【问题讨论】:

    标签: json grails groovy hashmap


    【解决方案1】:

    请注意,buzzProperties 不是 Map,而是 List{}[])。这就是为什么铸造无法进行的原因。将buzzProperties 类型更改为List 或发送有效的Map

    编辑

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

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

    【讨论】:

    • 感谢@Opal (+1) - 我不能(轻松)更改 Grails 控制器,但可以轻松更改 JSON。 buzzProperties 对象在 JSON 中需要是什么样子才能成为有效的地图?
    • 如果你想坚持地图列表,你也可以用类似jsonObject.buzzProperties.sum()
    • @cfrick 如果列表中的项目具有相同的键,那是个坏主意。它首先应该是一个 json 对象。
    • 另一个让您在Stuff 中保留buzzProperties 作为Map 并保留从服务器返回的地图列表格式的选项是为此添加一个setter - @987654335 @。循环遍历每一个并一次设置一个值。 Groovy 编译器仍应生成 void setBuzzProperties(Map props) { ... }Map getBuzzProperties() { ... },但请确保是这种情况(例如,使用 JD-GUI)并在需要时显式添加该设置器。
    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 2019-06-17
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多