SwiftyJSON
SwiftyJSON упрощает работу с данными JSON в Swift.
Платформа | Статус сборки |
---|---|
OS | |
Linux |
Swift очень строг в отношении типов. Но хотя явное типизирование полезно для предотвращения ошибок, оно становится неудобным при работе с JSON и другими областями, которые по своей природе неявны в отношении типов.
Возьмём, к примеру, Twitter API. Допустим, мы хотим получить значение «name» пользователя из твита в Swift (согласно Twitter API).
Код будет выглядеть так:
if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
let user = statusesArray[0]["user"] as? [String: Any],
let username = user["name"] as? String {
// Наконец-то мы получили имя пользователя
}
Это нехорошо.
Даже если мы используем опциональную цепочку, это будет беспорядочно:
if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String {
// Вот наше имя пользователя
}
Нечитаемый беспорядок — для чего-то, что должно быть простым!
Со SwiftyJSON всё, что вам нужно сделать, это:
let json = try? JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Теперь у вас есть значение
}
И не беспокойтесь о дополнительной упаковке. Это делается автоматически.
let json = try? JSON(data: dataFromNetworking)
let result = json[999999]["wrong_key"]["wrong_name"]
if let userName = result.string {
//Успокойтесь, расслабьтесь, свойство ".string" по-прежнему выдаёт правильный тип Optional String с безопасностью
} else {
//Выведите ошибку
print(result.error)
}
Вы можете использовать CocoaPods для установки SwiftyJSON
, добавив его в свой Podfile
:
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftyJSON', '~> 4.0'
end
Вы можете использовать Carthage, чтобы установить SwiftyJSON
, добавив его в свой Cartfile
:
github "SwiftyJSON/SwiftyJSON" ~> 4.0
Если вы используете Carthage для создания своих зависимостей, убедитесь, что вы добавили SwiftyJSON.framework
в раздел «Связанные фреймворки и библиотеки» вашей цели и включили их в свою фазу копирования фреймворка Carthage. ```
// Bool
if let id = json["user"]["is_translator"].bool {
// Do something you want
} else {
// Print the error
print(json["user"]["is_translator"].error!)
}
// Int if let id = json["user"]["id"].int { // Do something you want } else { // Print the error print(json["user"]["id"].error!) } ...
#### Non-optional getter
Non-optional getter is named `xxxValue`
// If not a Number or nil, return 0 let id: Int = json["id"].intValue
// If not a String or nil, return "" let name: String = json["name"].stringValue
// If not an Array or nil, return [] let list: Array = json["list"].arrayValue
// If not a Dictionary or nil, return [:] let user: Dictionary<String, JSON> = json["user"].dictionaryValue
#### Setter
json["name"] = JSON("new-name") json[0] = JSON(1)
json["id"].int = 1234567890 json["coordinate"].double = 8766.766 json["name"].string = "Jack" json.arrayObject = [1,2,3,4] json.dictionaryObject = ["name":"Jack", "age":25]
#### Raw object
let rawObject: Any = json.object
let rawValue: Any = json.rawValue
//convert the JSON to raw NSData do { let rawData = try json.rawData() //Do something you want } catch { print("Error (error)") }
//convert the JSON to a raw String if let rawString = json.rawString() { //Do something you want } else { print("json.rawString is nil") }
#### Existence
// shows you whether value specified in JSON or not if json["name"].exists()
#### Literal convertibles
For more info about literal convertibles: Swift Literal Convertibles
// StringLiteralConvertible let json: JSON = "I'm a json"
// IntegerLiteralConvertible let json: JSON = 12345
// BooleanLiteralConvertible let json: JSON = true
// FloatLiteralConvertible let json: JSON = 2.8765
// DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"]
// ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"]
// With subscript in array var json: JSON = [1,2,3] json[0] = 100 json[1] = 200 json[2] = 300 json[999] = 300 // Don't worry, nothing will happen
// With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] json["name"] = "Mike" json["age"] = "25" // It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json
// Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" let path: [JSONSubscriptType] = ["list",3,"what"] json[path] = "that"
// With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ "user": user.object, // use user.object instead of just user "apikey": "supersecretapitoken" ]
#### Merging
It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON.
If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment:
- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value.
- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged.
In a case where two fields in a JSON have different types, the value will get always overwritten.
There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )