SWIFT JSON

http://qiita.com/susieyy/items/6cd0a2293555d5abb9c1
https://github.com/Ahmed-Ali/JSONExport
はじめに
JSONはVALUE部分の多様な型※とnilになる可能性もあるため、Swift言語のみでは扱いにくいところがあります。
そんな問題を解決する、パースしたJSONオブジェクトを扱いやすくするライブラリや、モデルにマッピングまで行うものまで、JSONを便利に扱えるライブラリをご紹介します。
※ String, Int, Float, Double, Array, Dictinary, etc
SwiftyJSON/SwiftyJSON ★3526
The better way to deal with JSON data in Swift.
パース後のJSONオブジェクトを扱いやすくするライブラリです。
Non-optional getterでVALUEがnilの場合でもデフォルト値で扱えるのは便利です。Arrayに要素数を超えた添字でアクセスしてもクラッシュせずにerrorオブジェクトを返すところも親切 です。
Usage
let json = JSON(data: dataFromNetworking)

// or

let json = JSON(jsonObject)

//With a int from JSON supposed to an Array
let name = json[0].double

//With a string from JSON supposed to an Dictionary
let name = json[“name”].stringValue

//With an array like path to the element
let path = [1,”list”,2,”name”]
let name = json[path].string
//Just the same
let name = json[1][“list”][2][“name”].string

//With a literal array to the element
let name = json[1,”list”,2,”name”].string
//Just the same
let name = json[1][“list”][2][“name”].string

//With a Hard Way
let name = json[[1,”list”,2,”name”]].string
SwiftyJSON/Alamofire-SwiftyJSON ★308
Alamofire extension for serialize NSData to SwiftyJSON
SwiftyJSONはオフィシャルでAlamofireと連携するライブラリも提供しています。
Usage
Alamofire.request(.GET, “http://httpbin.org/get“, parameters: [“foo”: “bar”])
.responseSwiftyJSON { (request, response, json, error) in
println(json)
println(error)
}
owensd/json-swift ★546
A basic library for working with JSON in Swift.
パース後のJSONオブジェクトを扱いやすくするライブラリです。
できることはSwiftyJSONに似ています。ドキュメントも少なめです。
Usage
if let stat = json[“stat”].string {
println(“stat = ‘(stat)’”)
// prints: stat = ‘ok’
}

// Retrieve error information from a missing key lookup
let stat = json[“stats”]
if let value = stat.string {
println(“stat = ‘(value)’”)
}
else if let error = stat.error {
println(“code: (error.code), domain: ‘(error.domain)’, info: ‘(error.userInfo[LocalizedDescriptionKey]!)’”)
// prints: code: 6, domain: ‘com.kiadsoftware.json.error’, info: ‘There is no value stored with key: ‘stats’.’
}

// Iterate over the contents of an array**
if let blogs = json[“blogs”][“blog”].array {
for blog in blogs {
println(“blog: (blog)”)
}
}
thoughtbot/Argo ★490
Functional JSON parsing library for Swift
マッピング定義に基づいてモデルへマッピングを行うライブラリです。
モデルの仕様を継承ではなくて、プロトコル準拠でおこなっています。
マッピングの定義を独自の演算子記法で記述します。HaskellのJSONライブラリAesonの影響を受けているそうです。createメソッドの部分が少し冗長な記述に感じています。
Usage
struct User {
let id: Int
let name: String
let email: String?
let role: Role
let companyName: String
let friends: [User]
}

extension User: JSONDecodable {
static func create(id: Int)(name: String)(email: String?)(role: Role)(companyName: String)(friends: [User]) -> User {
return User(id: id, name: name, email: email, role: role, companyName: companyName, friends: friends)
}

static func decode(j: JSONValue) -> User? {
return User.create
<^> j <| “id”
<*> j <| “name”
<*> j <|? “email” // Use ? for parsing optional values
<*> j <| “role” // Custom types that also conform to JSONDecodable just work
<*> j <| [“company”, “name”] // Parse nested objects
<*> j <|| “friends” // parse arrays of objects
}
}

// Wherever you receive JSON data:

let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: .None)

if let j: AnyObject = json {
let value = JSONValue.parse(j)
let user = User.decode(value)
}
Hearst-DD/ObjectMapper ★428
JSON Object mapping written in Swift.
マッピング定義に基づいてモデルへマッピングを行うライブラリです。
モデルの仕様を継承ではなくて、プロトコル準拠でおこなっています。
マッピング定義の記述がとてもシンプルでありながら、可読性も高いです。
日本語でソースコードの解説をしてくださっている方がいらっしゃいます。
情弱がSwift用のObjectMapper読んでみた
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: NSDate?

required init?(_ map: Map) {
    mapping(map)
}

// Mappable
func mapping(map: Map) {
    username    <- map["username"]
    age         <- map["age"]
    weight      <- map["weight"]
    arrary      <- map["arr"]
    dictionary  <- map["dict"]
    best_friend <- map["best_friend"]
    friends     <- map["friends"]
    birthday    <- (map["birthday"], DateTransform())
}

}

let user = Mapper().map(string: JSONString)

struct Temperature: Mappable {
var celcius: Double?
var fahrenheit: Double?

init(){}

init?(_ map: Map) {
    mapping(map)
}

mutating func mapping(map: Map) {
    celcius     <- map["celcius"]
    fahrenheit  <- map["fahrenheit"]
}

}
isair/JSONHelper ★375
Lightning fast JSON deserialization and value conversion library for iOS & OS X written in Swift.
マッピング定義に基づいてモデルへマッピングを行うライブラリです。
モデルの仕様を継承ではなくて、プロトコル準拠でおこなっています。
マッピング定義とJSONオブジェクトからのモデルの作成を独自の演算子で行っています。
Usage
{
“books”: [
{
“author”: “Irvine Welsh”,
“name”: “Filth”
},
{
“author”: “Bret Easton Ellis”,
“name”: “American Psycho”
}
]
}
class Book: Deserializable {
var author: String? // You can also use let instead of var if you want.
var name: String?

required init(data: [String: AnyObject]) {
    author <<< data["author"]
    name <<< data["name"]
}

}
AFHTTPRequestOperationManager().GET(
http://yoursite.com/your-endpoint/
parameters: nil,
success: { operation, data in
var books: [Book]?
books <<<<* data[“books”]

    if let books = books {
        // Response contained a books array, and we deserialized it. Do what you want here.
    } else {
        // Server gave us a response but there was no books key in it, so the books variable
        // is equal to nil. Do some error handling here.
    }
},
failure: { operation, error in
    // Handle error.

})
dankogai/swift-json ★373
Even Swiftier JSON Handler
パース後のJSONオブジェクトを扱いやすくするライブラリです。
danさんによる国産のライブラリです。
400行ほどのコードで実装されており読むことで勉強にもなります。
Usage
let obj:[String:AnyObject] = [
“array”: [JSON.null, false, 0, “”, [], [:]],
“object”:[
“null”: JSON.null,
“bool”: true,
“int”: 42,
“double”: 3.141592653589793,
“string”: “a α\t弾\n?”,
“array”: [],
“object”: [:]
],
“url”:”http://blog.livedoor.com/dankogai/
]

let json = JSON(obj)

json[“object”][“null”].asNull // NSNull()
json[“object”][“bool”].asBool // true
json[“object”][“int”].asInt // 42
json[“object”][“double”].asDouble // 3.141592653589793
json[“object”][“string”].asString // “a α\t弾\n?”

json[“array”][0].asNull // NSNull()
json[“array”][1].asBool // false
json[“array”][2].asInt // 0
json[“array”][3].asString // “”
Ahmed-Ali/JSONExport ★410
JSONExport is a desktop application for Mac OS X which enables you to export JSON objects as model classes
JSONの文字列を解析してコードを作成してくれる便利なツールです。
以下の形式を出力することができます。
Swift Classes.
Swift Classes - To use with SwiftyJSON library.
Swift Classes - To use with Realm.
Swift - CoreData.
Swift Sturcutres.
Objective-C - iOS.
Objective-C - MAC.
Objective-C - CoreData.
Objective-C - To use with Realm.
72693010-7713-11e4-9e42-625a8590424a.png
Ref Swift Networking Library
Alamofire/Alamofire
Ref ObjC JSON Library
matthewcheok/Realm-JSON
A concise Mantle-like way of working with Realm and JSON.
Mantle/Mantle
Mantle not compatible with Swift #344
gonzalezreal/Overcoat
RestKit/RestKit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值