我正在使用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";
}
)
答案 0 :(得分:0)
根据评论我理解结构实际上是这样的:
[{
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)
}
}
}