Arrays Swift:如果服务器的JSON响应是';它被包裹在一个数组中?
这里是Swift n00b 我从服务器得到的响应如下:Arrays Swift:如果服务器的JSON响应是';它被包裹在一个数组中?,arrays,json,swift,Arrays,Json,Swift,这里是Swift n00b 我从服务器得到的响应如下: [ { "foo": [], "bar":"asdf", ... } ] 现在我了解了如何解析常规JSON,但当它有一个数组作为基本元素时就不知道了 以下是我迄今为止使用的代码,适用于常规JSON: let task = session.dataTask(with: urlRequest) { (data, response, error) in // check for any err
[
{
"foo": [],
"bar":"asdf",
...
}
]
现在我了解了如何解析常规JSON,但当它有一个数组作为基本元素时就不知道了
以下是我迄今为止使用的代码,适用于常规JSON:
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling POST on \(String(describing: urlRequest.url?.absoluteURL))")
print(error!)
return
}
// make sure we got the data
guard let responseData = data else {
print("Error: did not receive data")
return
}
let responseString = String(data: responseData, encoding: String.Encoding.utf8) as String!
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
... // do whatever with the response
} catch {
print("an error occurred")
return
}
}
task.resume()
我从中得到的错误是“尝试将数据转换为JSON时出错”
我能想到的解析该响应的最简单方法是生成一个从1到长度-1的子字符串,然后对其进行解析,但这似乎并不特别安全
有什么方法可以将响应解析为一个
[字典]
?您的JSON是常规JSON。顶级数组与字典一样有效(和常规)
只需相应地更新您的演员阵容:
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [[String: Any]] else {
这表示您有一个字典数组。现在您可以根据需要迭代该数组并获取每个字典。您所说的“常规JSON”是什么意思?即“常规JSON”“。JSON结构的顶层可以是数组或字典。@rmaddy好的,我不确定。我所说的常规JSON是指在顶层带有字典的JSON。