将alamofire json响应转换为变量

时间:2018-04-09 21:07:07

标签: ios json swift alamofire

我有一个问题,我已经多次询问过stackoverflow,我已经尝试了所有这些,但没有一个有效。所以我很想再次总结这个问题,并试着更准确地描述它。

我正在构建一个应用程序,将图片发送到python后端,以获取xcode swift中的图像识别结果。

我正在使用Alamofire上传, 这是上传部分:

Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData!, withName: "pic", fileName: "filename.png", mimeType: "image/png")

        }, to: "http:123456.com/image",
           method: .post,
           encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    debugPrint(response)
                }

            case .failure(let encodingError):
                print(encodingError)
            }

这是我从服务器端获得的json响应:

[Response]: <NSHTTPURLResponse: 0x600000237de0> { URL: 1234/image } { Status Code: 200, Headers {
    "Content-Length" =     (
        348
    );
    "Content-Type" =     (
        "text/html; charset=utf-8"
    );
    Date =     (
        "Mon, 09 Apr 2018 20:59:30 GMT"
    );
    Server =     (
        "Werkzeug/0.12.2 Python/2.7.12"
    );
} }
[Data]: 348 bytes
[Result]: SUCCESS: {
 "prediction": [
  {
   "name": "marshmallow", 
   "value": 0.2800232470035553
  }, 
  {
   "name": "caesar salad", 
   "value": 0.090629942715168
  }, 
  {
   "name": "egg", 
   "value": 0.07480788230895996
  }, 
  {
   "name": "apple", 
   "value": 0.049235329031944275
  }, 
  {
   "name": "chickpea", 
   "value": 0.04692944884300232
  }
 ]
}
[Timeline]: Timeline: { "Request Start Time": 545000363.584, "Initial Response Time": 545000363.642, "Request Completed Time": 545000370.462, "Serialization Completed Time": 545000370.487, "Latency": 0.058 secs, "Request Duration": 6.879 secs, "Serialization Duration": 0.025 secs, "Total Duration": 6.903 secs }

所以,我想要的目的只是打印第一个预测名称的名称。

就像输出

一样

结果是棉花糖,值为0.28

我尝试了几种方法:

首先,我希望有一个结构将名称存储为字符串,值为double,并使用循环来解析它。但无论我尝试什么,我总是得到一个&#34; null&#34;作为输出,或什么都没有。

对此有何建议?提前谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

upload.responseJSON { response in
if let result = response.result.value {
                        let json = result as! [String: Any]
                        if let predictionArray = json["prediction"] as? [[String: Any]],
                            let firstPrediction = predictionArray.first {
                            print(firstPrediction)
                        }
                        print(json)
                    }
                }