将 Alamofire JSON 响应转换为变量



我有一个问题,我已经在stackoverflow上问过几次了,我已经尝试了所有这些问题,但没有一个有效。因此,我很想再总结一下这个问题,并尝试更准确地描述它。

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

我正在使用阿拉莫火上传,这是上传部分:

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

我尝试了几种方法:

首先,我想有一个结构来将名称存储为字符串,值存储为双精度,并使用循环来解析它。但是无论我尝试什么,我总是得到一个"null"作为输出,或者什么都没有。

对此有什么建议吗?提前谢谢。

试试这个:

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

最新更新