如何解析alamofire返回json到Swift中的字符串数组?

问题描述:

在我的swift应用程序中,我使用SwiftyJSONAlamofire如何解析alamofire返回json到Swift中的字符串数组?

我有回来从我的后端应用一个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(...)否则,您得做JSON(data: $0.data)您改为拨打.response(...)。)

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 } 
    ) 
    } 
} 
+0

谢谢,效果不错:) – user3766930