从 json 文件 swift 获取特定值
Getting specific value from json file swift
我正在尝试使用他们的 API 获取 Instagram 用户名,这是我的代码:
private func getUserInfo() {
let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/v1/users/self/?access_token=\(Settings.Access_Token)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
})
dataTask.resume()
}
下面的打印语句returns是有效的,但是我不知道如何访问和存储用户名值,我不明白其他人对类似主题的回应:
{
"data": {
"id": "253876051",
"username": "bruncheveuxcourtsyeuxverts",
"profile_picture": "https:\/\/scontent.cdninstagram.com\/vp\/7eb0427fdd53a5b319d04c22af1c9f63\/5C977089\/t51.2885-19\/s150x150\/46724860_307687986508947_185550859294212096_n.jpg?_nc_ht=scontent.cdninstagram.com",
"full_name": "Lo\u00efc Buckwell",
"bio": "Gogole de p\u00e8re en fils",
"website": "",
"is_business": false,
"counts": {
"media": 16,
"follows": 106,
"followed_by": 406
}
},
"meta": {
"code": 200
}
}
您可以使用json序列化将json对象转换为swift字典对象。
For example
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
另一种选择是在 Swift:
中使用 Codable 系统
struct Counts: Codable {
enum CodingKeys: String, CodingKey {
case followedBy = "followed_by"
case follows
case media
}
let followedBy: Int
let follows: Int
let media: Int
}
struct InstagramUser: Codable {
enum CodingKeys: String, CodingKey {
case bio
case counts
case fullName = "full_name"
case id
case isBusiness = "is_business"
case profilePicture = "profile_picture"
case username
case website
}
let bio: String
let counts: Counts
let fullName: String
let id: String
let isBusiness: Bool
let profilePicture: String
let username: String
let website: String
}
struct Meta: Codable {
let code: Int
}
struct Output: Codable {
enum CodingKeys: String, CodingKey {
case user = "data"
case meta
}
let user: InstagramUser
let meta: Meta
}
现在在您的街区内您可以使用:
let ouptut = try! JSONDecoder().decode(Output.self, from: data)
let fullName = output.user.fullName
我正在尝试使用他们的 API 获取 Instagram 用户名,这是我的代码:
private func getUserInfo() {
let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/v1/users/self/?access_token=\(Settings.Access_Token)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
})
dataTask.resume()
}
下面的打印语句returns是有效的,但是我不知道如何访问和存储用户名值,我不明白其他人对类似主题的回应:
{
"data": {
"id": "253876051",
"username": "bruncheveuxcourtsyeuxverts",
"profile_picture": "https:\/\/scontent.cdninstagram.com\/vp\/7eb0427fdd53a5b319d04c22af1c9f63\/5C977089\/t51.2885-19\/s150x150\/46724860_307687986508947_185550859294212096_n.jpg?_nc_ht=scontent.cdninstagram.com",
"full_name": "Lo\u00efc Buckwell",
"bio": "Gogole de p\u00e8re en fils",
"website": "",
"is_business": false,
"counts": {
"media": 16,
"follows": 106,
"followed_by": 406
}
},
"meta": {
"code": 200
}
}
您可以使用json序列化将json对象转换为swift字典对象。
For example
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
另一种选择是在 Swift:
中使用 Codable 系统struct Counts: Codable {
enum CodingKeys: String, CodingKey {
case followedBy = "followed_by"
case follows
case media
}
let followedBy: Int
let follows: Int
let media: Int
}
struct InstagramUser: Codable {
enum CodingKeys: String, CodingKey {
case bio
case counts
case fullName = "full_name"
case id
case isBusiness = "is_business"
case profilePicture = "profile_picture"
case username
case website
}
let bio: String
let counts: Counts
let fullName: String
let id: String
let isBusiness: Bool
let profilePicture: String
let username: String
let website: String
}
struct Meta: Codable {
let code: Int
}
struct Output: Codable {
enum CodingKeys: String, CodingKey {
case user = "data"
case meta
}
let user: InstagramUser
let meta: Meta
}
现在在您的街区内您可以使用:
let ouptut = try! JSONDecoder().decode(Output.self, from: data)
let fullName = output.user.fullName