SwiftyJSON

  • 与NSJSONSerialization比较

NSJSONSerialization的方法:

//解析Json
let jsonStr = "{\"usr\":\"张三\",\"info\":{\"number\":\"188\",\"address\":\"51load\"}}"
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)

let json : AnyObject! = try? NSJSONSerialization.JSONObjectWithData(jsonData!, options:NSJSONReadingOptions.AllowFragments)
print(json)

let uname : AnyObject = json.objectForKey("usr")!
let mobile : AnyObject = json.objectForKey("info")!.objectForKey("address")!
print("get Json Object:"); print("uname: \(uname), mobile: \(mobile)")

// 生成Json
let user = [
    "usr": "",
    "info": ["psw": "123", "home": "001"]
]

if (NSJSONSerialization.isValidJSONObject(user)) {
    let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(user, options: [])
    let str = NSString(data:data, encoding: NSUTF8StringEncoding)
    print(str)
}

NSJSONSerialization使用起来还是不太爽,下面对比下SwiftyJSON:

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
  //这个代码基本看不懂了啊!
}
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //就这么简单取到了。
}

安装方法

  • 方法一,直接用swift源码

可以将SwiftyJSON-master/Source/SwiftyJSON.swift 拷贝到自己的项目中

  • 方法二,可以将的SwiftyJSON整个拿去当项目依赖

将SwiftyJSON-master整个拷贝到我们的项目根目录中
将SwiftyJSON-master/SwiftyJSON.xcodeproj添加到我们的项目中
最后点击我们的工程在General->

clipboard.png

clipboard.png

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
    pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end

使用方法

let jsonStr = "{\"usr\":\"张三\",\"info\":{\"number\":[\"188\",\"189\"],\"address\":\"51load\"}}"
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)

let json = JSON(data: jsonData!)

print("1", json["usr"].string) //1 Optional("张三")
print("1", json["usr"]) //1 张三
print("1", json["usr"].stringValue) //1 张三

print("2", json["info"]["number"][1].int) //2 nil
print("2", json["info"]["number"][1].intValue) //2 189
print("2", json["info"]["number"].arrayValue) //2 [188, 189]

print("3", json["info", "number", 1].stringValue) //3 189
print("3", json[["info", "number", 1]]) //3 189

for (key, subJson) in json["info"] { //loop for dictionary
    print("4", key, subJson)
}

let dictJson = JSON(["name": "jack", "age": 25])
if let name = dictJson["address"].string {
    print("5", name)
} else {
    print("5", dictJson["address"].error)
}

var json3: JSON = [1,2,3]
json3[0] = 100
json3[2] = 300
print("6", json3)

RichardXG
337 声望19 粉丝