gpt4 book ai didi

json - Swift json解析错误: Could not cast value of type NSCFConstantString to NSArray

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:05 26 4
gpt4 key购买 nike

我在使用 swift 代码解析 json 时遇到了一些问题。

json示例

{"responce": "ok","orders": [{"id":"1"), {"id":"2"}, {"id":"3"} ]}

这段代码工作正常

let dataArray: NSArray = jsonResult["orders"] as! NSArray

但是如果我得到 {"responce": "ok","orders": ""} 我得到了 error: Could not cast value of type __NSCFConstantString (0x10c7bfc78) to NSArray (0x10c7c0470).

我能否以某种方式检查值是否为数组以避免崩溃?

最佳答案

是的,你可以通过这样做来检查值是否为 NSArray:

if let dataArray = jsonResult["orders"] as? NSArray {

}

如果 jsonResult["orders"] 的结果是一个 NSArray,那么将设​​置 dataArray,然后您将进入 if 语句。

关于json - Swift json解析错误: Could not cast value of type NSCFConstantString to NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29821440/

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