1

After reading up a bit on collections, I began to wonder if json deserialization was going to be an issue given that collections need to specify a type for the values they contain. And in the case of dictionaries, one would need to specify the type for both the key and the value.

After a bit of experimentation, I found that the following works:

let jsonString = "{\"bool\": true, \"num\": 1,\"string\": \"a string\"}"
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)

let valid = NSJSONSerialization.isValidJSONObject(json)

And when I use a playground (or am in the REPL), I get the following when printing out the contents of the json object:

["num": 1, "string": "a string", "bool": 1]

My question: is there may be a better way to handle this?

1
  • That's pretty much it, although I would tend to use optionals instead of implicitly unwrapped (? instead of !) And since it's a lot of arrays and dictionaries of AnyObject, there's a whole lot of casting going on. Commented Jun 8, 2014 at 19:02

1 Answer 1

1

I'd suggest typing your json object a little more:

let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? Dictionary<String, AnyObject?>

This will help you access elements by their key.

Sign up to request clarification or add additional context in comments.

1 Comment

Cannot conver the expression's type '$T4' to type 'Dictionary<String, AnyObject!>'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.