SwiftyJSON
SwiftyJSON is an open-source library that helps developers use JSON in Swift without much difficulty. Swift is very strict about types so, it is very difficult to work with JSON in Swift. SwiftyJSON provides a better way to deal with JSON data in Swift.
SwiftyJSON is a Swift framework which was built to remove the need for optional chaining in normal JSON serialization.
The problem with JSON in Swift
Before using SwiftyJSON, let’s see the mess a user can face while dealing with JSON in Swift. For example, your code would look like this if you find the name of the first book in a JSON object:
You can see that the above code is complicated and difficult to read.
By using SwiftyJSON, it will be highly simplified like this:
SwiftyJSON removes the requirement of checking every field, as it returns nil if any of them are invalid.
Download SwiftJSON
You can download or clone SwityJSON directly from GitHub:
https://github.com/SwiftyJSON/SwiftyJSON
How to use SwiftyJSON
To use SwiftyJSON, you have to download the correct version from the Git repository. Simply, drag the “SwiftyJSON.swift” into your project and import into your class:
You can create your own JSON object by using initializers. There are two ways to create your own JSON object:
Or
You can use subscripts to access your data.
You can parse your value to a certain data type, which will return an optional value:
You can also compile your paths into a swift Array:
It is same as:
SwiftyJSON has the functionality to print its own errors:
If you need to write to your JSON object, you can use subscripts again:
If you want the original String for the JSON, for example if you need to write it to a file, you can get the raw value.