简体   繁体   English

数据 > JSON - Swift3 - 转换和解析

[英]Data > JSON - Swift3 - Convert & Parse

having one heck of a time handling the response I get from my API within a Swift3 app I'm building.在我正在构建的 Swift3 应用程序中,我花了很多时间处理我从 API 获得的响应。

In the below screenshot, I am receiving Data from an httprequest using URLSession.shared, and passing it through to the handleSuccess method ... I am having issues simply converting to a JSON obj and accessing any of the key/values ...在下面的屏幕截图中,我使用 URLSession.shared 从 httprequest 接收数据,并将其传递给 handleSuccess 方法......我在转换为 JSON obj 并访问任何键/值时遇到问题......

试图解析

... ...

func handleSuccess(jsonResponse: Data)
{
    NSLog("Handle Success: \(jsonResponse)")

    do
    {
        let json = try JSONSerialization.jsonObject(with: jsonResponse, options: .allowFragments)
        NSLog("json: \(json)")

        // I simply want to:
        let firstName = json["firstName"]

try to parse your json into a dictionary first :首先尝试将您的 json 解析为字典:

var firstName = ""
if let dict = json as? [String : AnyObject] {
  firstName = dict["firstName"] as! String
}

...

UserManager.sharedInstance.firstName = firstName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM