4. JSON in Swift

JSONStringify and JSONParse functions

Santosh Rajan
Swift Programming
3 min readJun 19, 2014

--

Previous Posts

  1. Learn Swift by running Scripts
  2. Functional Swift
  3. More Functional Swift

In Swift you can use Objective-C classes. You can import builtin SDK frameworks/modules into Swift. Type the following and run the program.

import Foundation

Don’t be surprised if you get an error. (In case you got one).

JSON.swift:1:8: error: cannot load underlying module for ‘Foundation’
import Foundation
^
<unknown>:0: note: did you forget to set an SDK using -sdk or SDKROOT?
<unknown>:0: note: use “-sdk $(xcrun —show-sdk-path —sdk macosx)” to select the default OS X SDK installed with Xcode

To fix this set SDKROOT environment variable.

$ export SDKROOT=$(xcrun —show-sdk-path —sdk macosx)

The objective here is to wrap JSON stringify and parsing in Objective-C such that a person who knows Swift but not Objective-C can use the functions. Hence I will not be explaining the Objective-C part of the code here. Those who know Objective-C will understand the code.

JSONStringify is a function that will take a JSON Object and return a JSON String. But we need to get around a couple of problems first.

  1. A JSON Object’s root element must be an Array or Dictionary.
  2. The Array or Dictionary can contain elements of any Type.

Swift only allows typed Arrays and Dictionaries. However Swift allows us to use a Type called AnyObject in our Type definition. So if our Arrays are of Type [AnyObject], and Dictionaries are of Type [String, AnyObject] we are fine.

First we create an Array of Type AnyObject, and we populate it with a Dictionary of mixed type values.

The JSONStringify function takes an Object of Type AnyObject. This is important because the JSON Object could be an Array or Dictionary.

The second argument is a Bool. It has default value of false. So if you don’t specify the second parameter, variable prettyPrinted will be false.

prettyPrinted: Bool = false

The Return value is a String. If there is an error serialising, the function will return a null String “”. This way we can avoid using Optionals. You can check for a null String if you want to check for errors.

First we set up a Optional variable called options. Depending on prettyPrinted being true or false, options is set to either NSJSONWritingOptions.PrettyPrinted or nil.

let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)

Next we check if the value passed is a valid JSON Object. i.e. we need to make sure all the elements of the Object are convertible to valid JSON elements. Valid JSON elements are Dictionary, Array, String, Number, Boolean and null.

if NSJSONSerialization.isValidJSONObject(value)

For parsing JSON we need two functions that takes a String, and will parse and return an Array or Dictionary. Here is the code for JSONParseArray.

First we create a String containing valid JSON.

Then we parse the String using JSONParseArray to get an Array of Type [AnyObject]. Then we iterate over the array and print the Dictionary elements.

Note that in case of a parsing error the function returns an empty array, so the for loop will work without an error. It will not print anything. To check for error, check for an empty Array.

Notice that we explicitly cast the age to an Int. This is because the Type for numbers is NSNumber, so you have to cast it to the required type. Actually in this case the casting was not required because println would have printed it anyway. Strings are NSString, but you can use them as Swift Strings without explicitly casting them.

Here is JSONParseDictionary that works just like JSONParseArray. It returns an empty Dictionary in case of error.

Handling Errors

If you noticed in our stringify and parser functions we have a

do{
try
}catch{
}

This is because .JSONObjectWithData can throw an error , the try and catch is used to catch that error.

Thus, the error can be handled in the catch {} block.

In the above code, .JSONObjectWithData returns a nil in case of an error.

Next Post. 5. HTTP in Swift.

--

--

Santosh Rajan
Swift Programming

Founder www.geekskool.com. Programmer for over 30 years. Making better programmers is my passion. Bangalore. India. www.santoshrajan.com