Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift3 JSONSerialization with [String:Any] rather than NSDictionary

Tags:

json

swift

Say you have a string of json someText and you want to parse it to a dictionary. Previously I have done this...

let jsonResult: NSDictionary =
   try JSONSerialization.jsonObject(
      with: someText.data(using: .utf8)!,
      options: JSONSerialization.ReadingOptions.mutableContainers)
         as! NSDictionary

but that's just a crappy NSDictionary.

It would seem that you can indeed do this......

let jsonResult: [String:Any] =
   try JSONSerialization.jsonObject(
      with: someText.data(using: .utf8)!,
      options: JSONSerialization.ReadingOptions.mutableContainers)
         as! [String:Any]

so that's now a real Swift dictionary.

Does this work? Are there drastic efficiency differences, or perhaps other problems?

Confusingly to me,

  open class func jsonObject(with data: Data,
     options opt: JSONSerialization.ReadingOptions = []) throws -> Any

the call just returns Any anyways. So when you cast it to your [String:Any] or indeed NSDictionary, what's the process, what is best?

like image 701
Fattie Avatar asked Jun 12 '26 08:06

Fattie


1 Answers

Are there drastic efficiency differences

Yes there are.

NSDictionary completely lacks type information, native Swift collection types are much more efficient and highly recommended. And you get mutability for free using var. mutableContainers are useless in Swift anyway.

jsonObject(with data returns Any because the return type can be Dictionary, Array or even String/Number, the least common denominator is Any, cast it to the expected type.

like image 78
vadian Avatar answered Jun 15 '26 02:06

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!