gpt4 book ai didi

json - Grails 无法将 JSON 数组转换为 HashMap

转载 作者:行者123 更新时间:2023-12-02 15:00:31 25 4
gpt4 key购买 nike

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

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

在我的 Grails Controller 中,我有以下方法将此 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
}

当 Controller 方法执行时(当它收到请求时)我得到以下异常:
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。这里发生了什么?

最佳答案

请注意 buzzProperties不是 Map这是一个 List ( {}[] )。这就是为什么类型转换无法进行的原因。要么更改 buzzProperties输入 List或发送有效的Map .

编辑

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

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

关于json - Grails 无法将 JSON 数组转换为 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com