gpt4 book ai didi

json - 将 JSON 数据解析为 Swift 时遇到问题

转载 作者:行者123 更新时间:2023-11-30 11:02:42 28 4
gpt4 key购买 nike

我正在尝试将 Web 服务中的 JSON 数据解析到我的 Swift 中

我的网络浏览器上的 JSON 输出:

 [{"code":0,"message":"Check Username and Password....","userid":""}]

Swift 代码:

  Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON

{
response in
//printing response
print(response)

if let userJSON = response.result.value
{
let userdata:Dictionary = userJSON as! Dictionary<String, Any>
let message:Dictionary = userdata["message"] as! Dictionary<String, Any>

print(message)


}

我想在我的代码中使用 JSON 中的消息元素。但是我得到以下输出和错误:

    (
{
code = 1;
message = "Login Successfull";
userid = 236;
}
)
Could not cast value of type '__NSSingleObjectArrayI' (0x10fd94b98) to 'NSDictionary' (0x10fd958b8).
2018-11-03 20:15:10.762929+0530 testDisplayTable[44610:2871941]
Could not cast value of type '__NSSingleObjectArrayI' (0x10fd94b98) to 'NSDictionary' (0x10fd958b8).

如何成功获取message的值并打印?有人可以告诉我我的案例的正确代码吗?提前致谢!

最佳答案

这是一个数组而不是字典

if let userdata = userJSON as? [[String:Any]] { 
if let message = userdata[0]["message"] as? String {
print(message)
}
}

关于json - 将 JSON 数据解析为 Swift 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53132508/

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