SwiftJson使用

参考
https://github.com/SwiftyJSON/SwiftyJSON
http://tangplin.github.io/swiftyjson/
http://www.hangge.com/blog/cache/detail_968.html
https://stackoverflow.com/questions/36730721/how-to-convert-a-string-into-json-using-swiftyjson

构造创建JSON对象数据

(1)空的JSON对象

let json: JSON =  nil```

(2)使用简单的数据类型创建JSON对象

//StringLiteralConvertible
let json: JSON = "I'm a son"
//IntegerLiteralConvertible
let json: JSON = 12345
//BooleanLiteralConvertible
let json: JSON = true
//FloatLiteralConvertible
let json: JSON = 2.8765

(3)使用数组或字典数据创建JSON对象

//DictionaryLiteralConvertible
let json: JSON = ["I":"am", "a":"son"]
//ArrayLiteralConvertible
let json: JSON = ["I", "am", "a", "son"]
//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"

(4)字符串转json
JSON.parse方法

let jsong:JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]]
let jsonStr = jsong.description
let json = JSON.parse(jsonStr)
let name = json["name"].stringValue

let yourString = NSMutableString()
let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)
let json = JSON(data: dataToConvert!)
print("\nYour string: " + String(describing: json))

###取值

//方式1
let number = json[0]["phones"][0]["number"].stringValue
//方式2
let number = json[0,"phones",0,"number"].stringValue
//方式3
let keys:[JSONSubscriptType] = [0,"phones",0,"number"]
let number = json[keys].stringValue


let name = json["name"].intValue //***Value int类型非可选型
let name2 = json["name"].string //String 可选型
let name3 = json["name"] //JSON类型 非可选型

###与网络处理配合
(1)与URLSession结合

//创建URL对象
let url = URL(string:"http://www.hangge.com/getJsonData.php")
//创建请求对象
let request = URLRequest(url: url!)

let dataTask = URLSession.shared.dataTask(with: request,
completionHandler: {(data, response, error) -> Void in
if error != nil{
print(error)
}else{
let json = JSON(data: data!)
if let number = json[0]["phones"][0]["number"].string {
// 找到电话号码
print("第一个联系人的第一个电话号码:",number)
}
}
}) as URLSessionTask

//使用resume方法启动任务
dataTask.resume()

(2)与AFNetworking配合使用

let url2 = "http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=6c487bf940b7cfbb44411a2377550c96"
manger.get(url2, parameters: nil, progress: nil, success: { (dataTask, any) in
let json = JSON(any!)
let temp = json["list"][0]["main"]["temp"]
print(temp)
}) { (dataTask, error) in
print(error)
}


(3)与Alamofire结合

//创建URL对象
let url = URL(string:"http://www.hangge.com/getJsonData.php")!

Alamofire.request(url).validate().responseJSON { response in
switch response.result.isSuccess {
case true:
if let value = response.result.value {
let json = JSON(value)
if let number = json[0]["phones"][0]["number"].string {
// 找到电话号码
print("第一个联系人的第一个电话号码:",number)
}
}
case false:
print(response.result.error)
}
}

你可能感兴趣的:(SwiftJson使用)