【问题标题】:Parse JSON response into a data model with Swift (LinkedIn API)使用 Swift (LinkedIn API) 将 JSON 响应解析为数据模型
【发布时间】:2018-03-27 08:57:20
【问题描述】:

我正在使用 LinkedInSwift 在用户验证其凭据后获取用户数据。我已经能够打印出我的response,它显示了他们的数据。但我现在正试图将这些数据解析为数据模型。

我有一个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;
},

【问题讨论】:

  • 您可以添加您提供的 JSON 数据吗?
  • @ZonilyJame 请查看更新后的问题。
  • 你应该使用response.jsonObject 而不仅仅是response

标签: ios json swift linkedin-api


【解决方案1】:
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!
    })
}

【讨论】:

  • 它给了我一个错误说:'(key: AnyHashable, value: Any)' to expected argument type 'JSON' (aka 'Dictionary&lt;String, Any&gt;') 当我像这样将它转换为 JSON 时:let user = LinkedInData(json: response.jsonObject as! JSON) 并打印 user?.firstName 我得到 Optional("Joe") 它。
  • firstName 是可选的,打开它,可选的就会消失。
  • 我正在尝试像这样打开它self.textLbl.text = "Hello /\(String(describing: user?.firstName!))" 但它不起作用:/
  • 如果让 fName = user?.firstName { self.textLbl.text = fName }
猜你喜欢
  • 2017-05-24
  • 2019-07-19
  • 2020-08-26
  • 2017-02-17
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
相关资源
最近更新 更多