如何在 Swift 3 中解析来自 URL 的 JSON 数据

Posted

技术标签:

【中文标题】如何在 Swift 3 中解析来自 URL 的 JSON 数据【英文标题】:How to parse through JSON data from URL in Swift 3 【发布时间】:2017-08-16 18:10:05 【问题描述】:

我正在尝试遍历从 POST 到 URL 检索到的 JSON 字典。检索数据并将其序列化为 JSON 对象后,我无法访问数据的各个部分。

func retrieveLotStatus(lotNumber: String) 
    let allowedChars = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#-[] ").inverted)

    var url = URLRequest(url: URL(string: "fakeURLHere")!)
    let BodyData = "lotNum=" + lotNumber + "&field=" + PHASE.addingPercentEncoding(withAllowedCharacters: allowedChars)!
    url.httpMethod = "POST"
    url.httpBody = BodyData.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: url)  data, response, error in
        guard let data = data, error == nil else 
            print(error?.localizedDescription ?? "No Data")
            return
        
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        print(responseJSON)
        if let jsonData = responseJSON as? [String: Any] 
            if let ItemNumber = jsonData["ItemNumber"] as? [String: Any] 
                print(ItemNumber)
            
        
    
    task.resume()

这是打印响应以供参考时检索的 JSON 数据的示例

    Optional(<__NSArrayI 0x17d08c90>(

    Count = 4;
    ItemNumber = 1;
    PercentComplete = "100.00";
    Total = 4;
,

    Count = 1;
    ItemNumber = 10;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 10a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 11;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 11a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 4;
    ItemNumber = 1a;
    PercentComplete = "100.00";
    Total = 4;
,

    Count = 2;
    ItemNumber = 2;
    PercentComplete = "100.00";
    Total = 2;
,

    Count = 2;
    ItemNumber = 2a;
    PercentComplete = "100.00";
    Total = 2;
,

    Count = 1;
    ItemNumber = 3;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 3a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 4;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 4a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 5;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 5a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 6;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 6a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 7;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 7a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 8;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 8a;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 9;
    PercentComplete = "100.00";
    Total = 1;
,

    Count = 1;
    ItemNumber = 9a;
    PercentComplete = "100.00";
    Total = 1;

)
)

我正在尝试遍历每个对象并将值附加到表中。但是,在我将它们格式化为 UITableCell 之前,我试图简单地读取每个 responseJSON["ItemNumber"]、responseJSON["Count"]、responseJSON["Total"] 和 responseJSON["PercentComplete"]

【问题讨论】:

responseData 是一个字典数组,而不是字典。 【参考方案1】:

问题是您试图将字典数组转换为字典。

if let jsonData = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [[String:Any]] 
    for item in jsonData 
        if let itemNumber = item["ItemNumber"] as? Int, let count = item["Count"] as? Int, let percentComplete = item["PercentComplete"] as? Double, let total = item["Total"] as? Int 
            //use data
        
    

还要确保您遵循 Swift 命名约定,即变量的小写。

【讨论】:

谢谢大卫,这帮助很大

以上是关于如何在 Swift 3 中解析来自 URL 的 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

使用swift 3点击单元格时如何在Avplayer中播放来自url的视频

如何解析这个 JSON 口袋妖怪字典?口袋妖怪 API (swift 3)

如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?

如何在swift中使用alamofire和swiftyjson解析分页url?

来自 URL 的 Youtube 视频 ID - Swift3

来自 url 的 swift 3 json 无法获取单元格 uitableview