加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SWIFT JSON

发布时间:2020-12-14 02:33:19 所属栏目:百科 来源:网络整理
导读:http://qiita.com/susieyy/items/6cd0a2293555d5abb9c1 https://github.com/Ahmed-Ali/JSONExport はじめに JSONはVALUE部分の多様な型※とnilになる可能性もあるため、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,”name”].string
//Just the same
let name = json[1][“list”][2][“name”].string

//With a Hard Way
let name = json[[1,”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,“”,[],[:]],
“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读