使用Swift(LinkedIn API)将数据模型中的JSON响应解析为
我使用LinkedInSwift在用户数据通过身份验证后获取其数据。我已经能够打印出显示其数据的我的response
。但我现在试图将这些数据解析为数据模型。使用Swift(LinkedIn API)将数据模型中的JSON响应解析为
我有一个User
类:
typealias JSON = [String: Any]
class User {
var id: String?
var firstName: String?
var lastName: String?
init(json: JSON) {
guard let id = json["id"] as? String, let firstName = json["firstName"] as? String, let lastName = json["lastName"] as? String else { return }
self.id = id
self.firstName = firstName
self.lastName = lastName
}
,这里是可以得到方法LinkedIn:
linkedinHelper.authorizeSuccess({ (lsToken) -> Void in
//Login success lsToken
print("User has logged in succesfully!")
//Check if the user user is logged in and perform and action if they are.
if self.linkedinHelper.lsAccessToken != nil {
self.linkedinHelper.requestURL("https://api.linkedin.com/v1/people/~:(id,first-name,last-name)?format=json",
requestType: LinkedinSwiftRequestGet,
success: { (response) -> Void in
print(response)
//Request success response
}) { [unowned self] (error) -> Void in
print(error.localizedDescription)
//Encounter error
}
} else {
}
}, error: { (error) -> Void in
print("Uh oh, there was an issue.")
//Encounter error: error.localizedDescription
}, cancel: {() -> Void in
print("Cancelled")
//User Cancelled!
})
}
我都对着这个不同的地方,但它似乎只是例子和文档停在response
或需要第三方框架来解析数据。有人可以帮助指导我实现我的目标吗?
更新打印response
的
结果:
<LSResponse - data: {
firstName = Joe;
id = htcxTEeLk4;
lastName = Smith;
},
class User {
var id: String?
var firstName: String?
var lastName: String?
init(json: JSON) {
guard let id = json["id"] as? String, let firstName = json["firstName"] as? String, let lastName = json["lastName"] as? String else { return }
self.id = id
self.firstName = firstName
self.lastName = lastName
}
linkedinHelper.authorizeSuccess({ (lsToken) -> Void in
//Login success lsToken
print("User has logged in succesfully!")
//Check if the user user is logged in and perform and action if they are.
if self.linkedinHelper.lsAccessToken != nil {
self.linkedinHelper.requestURL("https://api.linkedin.com/v1/people/~:(id,first-name,last-name)?format=json",
requestType: LinkedinSwiftRequestGet,
success: { (response) -> Void in
let user = User(json: response.jsonObject)
//Request success response
}) { [unowned self] (error) -> Void in
print(error.localizedDescription)
//Encounter error
}
} else {
}
}, error: { (error) -> Void in
print("Uh oh, there was an issue.")
//Encounter error: error.localizedDescription
}, cancel: {() -> Void in
print("Cancelled")
//User Cancelled!
})
}
它给我一个错误,说:''(键:AnyHashable,值:任何)“预期参数类型'JSON'(又名'字典
firstName是可选的,将其解包并且可选将消失。 – hemant3370
我试图像这样解开它'self.textLbl.text =“Hello/\(String(describe:user?.firstName!))”'但它不起作用:/ – Chace
你可以添加你所提供的JSON数据? –
@ZonilyJame请参阅最新的问题。 – Chace
你应该使用'response.jsonObject'而不是'response' –