Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-02-09

JSON + Swift = SwifterJSON

I just released a beta of my SwifterJSON project on github.

SwifterJSON is a single class JSON framework written -of course- in Swift. There are existing frameworks, and Apple themselves have a JSON parser in Cocoa. Still I wanted to use JSON slightly different and thought it would be a suitable vehicle to start programming in Swift.

SwifterJSON is slightly different in the sense that it creates a JSON hierarchy as a top level object that can be written to or read from. The top level object can be created from naught, or it can be build from an existing string (or file).

Access to the hierarchy is intended to use the subscript model.

A minimum implementation would be like this (after adding the SwifterJSON file to the project):

        let top = SwifterJSON.createJSONHierarchy()
        top["books"][0]["title"].stringValue = "THHGTTG"

        let myJsonString = top.description

The myJsonString will then contain: "{"books":[{"title":"THHGTTG"}]}"

To parse the above JSON string the following code can be used:

        let (topOrNil, errorOrNil) = SwifterJSON.createJsonHierarchyFromString(myJsonString)
        if let top = topOrNil {
            if let title = top["books"][0]["title"].stringValue {
                println("The title of the first book is: " + title)
            } else {
                println("The title of the first book in myJsonString was not found")
            }
        } else {
            println(errorOrNil!)
        }

When reading a value from a JSON hierarchy it is importent to always check for nil. Remember that a JSON string is often an input from the external world, and we need to make sure that our software handles errors that we receive from the outside world gracefully.

If you are curious to see how SwifterJSON would work in your projects, please go and take a look at it on github.

Oh, and tell me what you think of it....

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment