0

i am trying to parse JSON data from web service into my Swift

JSON Output on my web browser:

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

Swift Code:

  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)


    }

I want to use message element from the JSON for my code. However i get the following output and error:

    (
    {
    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).

How do I successfully get the value of message and print? Can someone please show me the correct code for my case. Thanks in advance!

  • Rather than changing the Swift code (you have to change the type of `message` anyway) a more efficient solution is to change the php code on the server to send a dictionary. – vadian Nov 03 '18 at 16:50
  • Possible duplicate of [How do I use JSON element with alamofire](https://stackoverflow.com/questions/53101764/how-do-i-use-json-element-with-alamofire) – Mikhail Sein Nov 07 '18 at 09:17

1 Answers1

0

It's an array not dictionary

if let userdata = userJSON as? [[String:Any]] { 
   if let message = userdata[0]["message"] as? String {
      print(message)
   }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87