尝试使用 Alamofire 在 Swift 3 中解析 JSON

大流士

我正在使用 Alamofire 调用我的 API,它返回以下 JSON:

{
    outer =         {
        height = 3457;
        width = 2736;
    };
    cost = 220;
    name = "Mega";
},
    {
    outer =         {
        height = 275;
        width = 300;
    };
    cost = 362;
    name = "Ultra";
},

例如,我想获取名称和高度并将它们存储到数组中。

这是我用来获取高度的相关代码:

 if let url = URL(string: "LINKTOAPI") {
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = HTTPMethod.get.rawValue
        urlRequest.addValue(apiKey, forHTTPHeaderField: "user-key")
        urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

        Alamofire.request(urlRequest).responseJSON {response in
            if let result = response.result.value as? [String:Any],
                let main = result["outer"] as? [[String:String]]{
                for obj in main{
                    print(obj["height"])                       
                }
            }
 }

下面的另一个例子:

https://stackoverflow.com/questions/41462844/json-parsing-in-swift-3-using-alamofire

我使用上述示例尝试使用相关代码:

 Alamofire.request(urlRequest).responseJSON {response in
            if let jsonDict = response.result.value as? [String:Any],
                let dataArray = jsonDict["outer"] as? [[String:Any]] {
                let nameArray = dataArray.flatMap { $0["height"] as? String }
                print(nameArray)
            }

在这两个示例中,实际上没有打印任何内容,因此我不确定出了什么问题。任何建议表示赞赏

编辑:下面的完整 JSON

SUCCESS: (
        {
    outer =         {
        height = 3457;
        width = 2736;
    };
    cost = 220;
    name = "Mega";
 },
        {
    outer =         {
        height = 275;
        width = 300;
    };
    cost = 362;
    name = "Ultra";
 },
        {
    outer =         {
        height = 31;
        width = 56;
    };
    cost = 42;
    name = "Mini";
 }
)
爬行者说话

根据评论,我了解到结构实际上是这样的:

[{
    outer =         {
        height = 3457;
        width = 2736;
    };
    cost = 220;
    name = "Mega";
},
    {
    outer =         {
        height = 275;
        width = 300;
    };
    cost = 362;
    name = "Ultra";
}]

我仍然不完全理解您希望对所有这些变量做什么,但这里是您如何解析它们以打印height每个部分值,因为这似乎是您在示例中尝试做的:

//Here you safely unwrap all of the sections as an array of dictionaries
if let allSections = response.result.value as? [[String : Any]] {

    //Here we will loop through the array and parse each dictionary
    for section in allSections {
        if let cost = section["cost"] as? Int, let name = section["name"] as? String, let outer = section["outer"] as? [String : Any], let height = outer["height"] as? Int, let width = outer["width"] as? Int {
            //Inside here you have access to every attribute in the section

            print(height)
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章