swift - 如何将 alamofire 返回 json 解析为 Swift 中的字符串数组?

标签 swift swift3 alamofire swifty-json

在我的 swift 应用程序中,我使用了 SwiftyJSONAlamofire

我有一个从我的后端返回到应用程序的 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/

相关文章:

ios - Alamofire 不会发出 GET 请求,但会成功调用完成处理程序

swift - 如何从 NSDictionary swift 4 获取关键数据

swift - 如何在 Swift 3.0 中拖放 Sprite ?

ios - UISegmentedControl 标签不适合

ios - 调整 CVPixelBuffer 的大小

ios - Swift 在 Alamofire 参数中发送 bool 值

ios - Swift - Alamofire totalBytesExpectedToRead 返回 -1,即使设置了 Content-length

ios - UIButton 标题标签的不同大小的字符串

javascript - node.js/Swift/Stripe/Webtask 创建费用时出错

ios - 如何使用 swift 3 在 iOS 上散列文件?