M1xelated M1xelated - 1 month ago 34
JSON Question

Swift: Could not cast NSCFString to NSNumber when parsing JSON

I have a JSON object, I need to extract a float value from this.
The JSON looks like this:

{"ticker":{"base":"NLG","target":"USD","price":"0.05896390","volume":"","change":"-0.00044477"},"timestamp":1477232372,"success":true,"error":""}


My goal is to get the price as a float. I am able to retrieve the json and log it when not casted to a float it prints: Optional(0.05896390).

When I cast it as a float I get the warning:


could not cast value of type
NSCFString
to
NSNumber



let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String: AnyObject]
let tick = json["ticker"]!["price"]! as! Float
print(tick)

Answer

price is clearly a string. In a JSON object everything between double quotes is a string even it seems to be a number.

if let tick = json["ticker"] as? [String:Any], let price = tick["price"] as? String {
    print(Float(tick))
}

Since all values are String you can even cast the dictionary to more specific [String:String]

if let tick = json["ticker"] as? [String:String], let price = tick["price"] {
    print(Float(tick))
}

Notes:

  • Since you have to unwrap the optionals anyway do it safely with optional bindings.
  • In Swift 3 the JSON dictionary is [String:Any]
Comments