Jatin Chauhan Jatin Chauhan - 11 days ago 5
iOS Question

How to parse Data from server? App getting crash on read of data from dictionary

Here is my JSON data which I am getting from server.

{
"result": "SUCCESS",
"resultcode": "000",
"balance": "-32020",
"available": "-32020",
"reserved": 0
}


When I am trying to parse these JSON data, App crashed and throws
Could not cast value of type '__NSCFNumber' (0x1a17dab60) to 'NSString' (0x1a17e5798).


I know the issue is about data type. But when I get Positive value for
reserved
key in above JSON data, it shows string value in JSON data, but when i get Negative value of
reserved
key, it return
Numeric
data type.

Here is the code Which i am reading data.

self.response?.objectForKey("reserved") as! NSString


So How to deal with this kind of issue?

Answer

You can parse data using if let statements. Check below

if let reservedNum = JSON["reserved"] as? Double {
  print(reservedNum)
} else if let reservedString = JSON["reserved"] as? String {
  print(reservedString)
} else {
  print("Error Parsing Data") 
}    

if let safeResult = JSON["result"] as? String {
   print(safeResult)
} 

And same for the rest and handle the response in a Modal.

Comments