Jatin Chauhan Jatin Chauhan - 1 year ago 71
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
key in above JSON data, it shows string value in JSON data, but when i get Negative value of
key, it return
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 Source

You can parse data using if let statements. Check below

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

if let safeResult = JSON["result"] as? String {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download