在我的 swift
应用程序中,我使用了 SwiftyJSON
和 Alamofire
。
我有一个从我的后端返回到应用程序的 json:
{
"responses" : [
{
"labelAnnotations" : [
{
"mid" : "\/m\/01yrx",
"score" : 0.8735667499999999,
"description" : "cat"
},
{
"mid" : "\/m\/0l7_8",
"score" : 0.7697883,
"description" : "floor"
},
{
"mid" : "\/m\/01c34b",
"score" : 0.7577944,
"description" : "flooring"
},
{
"mid" : "\/m\/03f6tq",
"score" : 0.52875614,
"description" : "living room"
},
{
"mid" : "\/m\/01vq3",
"score" : 0.52516687,
"description" : "christmas"
}
]
}
]
}
我想构建一个包含上述每个描述的 Strings
数组。
我试着用代码解析它:
{
case .success:
print("sukces")
if let jsonData = response.result.value {
let data = JSON(jsonData)
print(data)
if let responseData = data["responses"] as? JSON{
if let responseData2 = responseData["labelAnnotations"] as? JSON{
for userObject in responseData2 {
print(userObject["description"])
}
}
}
}
case .failure(let error):
print("fail")
print(error)
}
}
但是 print(userObject)
行返回空字符串。如何显示每个描述?一旦我可以在控制台中打印它,我就会将它添加到我的数组中。
最佳答案
检查字典值是否为 JSON
类型似乎是这里的问题,因为所有 SwiftyJSON
这样做是为了省去使用 as 进行类型检查的麻烦吗? ...
。
我不熟悉图书馆,但我认为你所要做的就是:
(假设 response.result.value
返回一个字典,因为您使用了 .responseJSON
方法,例如 Alamofire.request(...) .responseJSON(...)
否则,如果您调用了 .response(...)
,则必须执行 JSON(data: $0.data)
。)
Alamofire.request(...).responseJSON { response in
if let dictionary = response.result.value {
let JSONData = JSON(dictionary)
let userObjects = JSONData["responses"][0]["labelAnnotations"].arrayValue.map(
{ $0["description"].stringValue }
)
}
}
关于swift - 如何将 alamofire 返回 json 解析为 Swift 中的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443240/