JSONObject is a simple JSON deserializer using Swift.
The implementation is minimal but very expressive easily extendable. One of the main features is the handling and trackdown of errors in the json objects.
To read a json file like this
[
{
"id": 1,
"name": "Sergio",
"weight": 70.5,
"photos": []
},
{
"id": 2,
"name": "Miguel",
"weight": 65.5,
"photos": [{
"url": "http://fake.com/miguel.jpeg",
"width": 100,
"height": 200
}]
}
]
You simple need to do this
guard let url = NSBundle.mainBundle().URLForResource("sample", withExtension: "json") else {
print("Sample.json not found")
return
}
do {
let users = try JSONObject(url: url)
for user in users {
let id = try user["id"].int()
let name = try user["name"].string()
let weight = try user["weight"].double()
print("\(id) : \(name)'s weight is \(weight)")
}
} catch {
print(error)
return
}
JSONObject can be initialized with an instance of AnyObject?, NSData? or NSURL
let jsonFromAnyObject = try JSONObject(json:object) // where object is an instance of AnyObject?
let jsonFromNSData = try JSONObject(data:data) // where data is an instance of NSData
let jsonFromNSURL = try JSONObject(url: url) // where url is an instance of NSURL
You can access JSON values by using subscripts.
Use a subscript with an integer or a string key depending on whether the JSON is an array or a dictionary.
let user = try users[0]
let name = try user["name"]
Each subscript call returns an instance of JSONObject to allow chaining.
let name = try users[0]["name"]
If the underlying JSON object is an array, you can iterate over it.
for user in users {
let name = try user["name"]
}
After you interate to the right location you can use any of these functions to get the final object
- dictionary()
- array()
- string()
- int()
- float()
- double()
- bool()
- null()
JSONObject also provides an helper method to covert to NSDate
- dateWithFormater(formmatter)
It any of the keys doesn't exist, an index is out of bounds or the type is incorrect JSONObject will trown a JSONValidationError that shows the type of error and where it happened
do {
let name = try users[0]["fullname"] // that's fine too
} catch {
print(error)//Prints Root[0]: Missing "fullname" element in dictionary.
}
To run the example project, clone the repo, and run pod install
from the Example directory first.
- iOS 8 and above
SVEJSONObject is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "SVEJSONObject"
Sérgio Estêvão, sergio.estevao@gmail.com
SVEJSONObject is available under the MIT license. See the LICENSE file for more info.