Book Image

Swift Essentials

By : Alex Blewitt, Bandlem Limited
Book Image

Swift Essentials

By: Alex Blewitt, Bandlem Limited

Overview of this book

Whether you are a seasoned Objective-C developer or new to the Xcode platform, Swift Essentials will provide you with all you need to know to get started with the language. Prior experience with iOS development is not necessary, but will be helpful to get the most out of the book.
Table of Contents (10 chapters)
9
Index

Parsing JSON

The most popular mechanism to send structured data over a network is to encode it in JSON, which stands for JavaScript Object Notation. This provides a hierarchical tree data structure that can store simple numeric, logical, and string-based types along with the array and dictionary representations.

Both Mac OS X and iOS come with a built-in parser for JSON documents, in the NSJSONSerialization class. This provides a means to parse a data object and return an NSDictionary that contains the key/value pairs of a JSON object or an NSArray to represent JSON arrays. Other literals are parsed and represented as the NSNumber or NSString values.

The JSON parser uses JSONObjectWithData to create an object from an NSData object containing a string. This is typically the format returned by network APIs and can be created from an existing string using dataUsingEncoding with one of the built-in encoding types, such as NSUTF8StringEncoding.

A simple JSON array of numbers can be parsed as follows...