Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

JSON and NSJSONSerialization


To serialize and deserialize JSON documents, we will use the NSJSONSerialization class. As we will see, it is much easier to use the NSJSONSerialization class with JSON documents than it is to use the NSXMLParser class with XML documents; however, it can be more error-prone when we try to access the information. Just remember to always check values that are defined as optional for null prior to accessing them.

The NSJSONSerialization class, unlike the NSXMLParser class, will parse the entire JSON document memory and then return a JSON object back to you; therefore, there is a lot less code to write.

The NSJSONSerialization class can parse JSON documents from an NSData object or through a stream. To parse JSON documents from the various sources, we use the NSJSONSerialization class with the appropriate static method:

  • JSONObjectWithData(_: options: error:): This initializer will parse a JSON document stored as an NSData object

  • JSONObjectWithStream(_: options: error...