我正在使用 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)
}
}
}
关于ios - 尝试使用 Alamofire 在 Swift 3 中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47599746/