无法将JSON数据解析为Swift

时间:2018-11-03 14:59:27

标签: json swift xcode alamofire

我正在尝试将来自Web服务的JSON数据解析为我的Swift

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

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

快捷代码:

  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中的message元素用于我的代码。但是我得到以下输出和错误:

    (
    {
    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的值并打印?有人可以告诉我正确的密码吗?预先感谢!

1 个答案:

答案 0 :(得分:0)

这是一个数组,而不是字典

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