我有一个问题,我已经问了好几次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
我试过几种方法:
首先,我希望有一个结构将名称存储为字符串,值存储为double,并使用循环来解析它。但无论我尝试了什么,我总是得到一个“空”作为输出,或者什么都没有。
有什么建议吗?提前谢谢。

最佳答案

试试这个:

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

关于ios - 将alamofire json响应转换为变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49741702/

10-12 00:33