ios - 将 Alamofire POST 的 JSON 响应转换为可以显示的变量

标签 ios json swift alamofire

我正在使用 Alamofire 从服务器获取响应。 以下是我使用的代码:

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

        }, to: "http://cse-jcui-08.unl.edu:8910/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

我的问题是,如何将名称和值保存为变量,以便可以在我的应用程序上显示它? 我这样做的方式,实际上我在 SwiftyJSON 上尝试了几次,

像这样:

struct Food {

                        var name: String
                        var value: String

                        init(name: String, value: String) {
                            self.name = name
                            self.value = value
                        }
                    }

                    let json = response.result.value
                    let name = json!["name"]

但是它给了我这样的错误:Cannot subscript a value of type 'String' with an index of 'String'

那么,有人愿意帮助我吗?提前致谢

最佳答案

以下是在 Swift 4 中使用 Codable 协议(protocol)进行原生 JSON 解析的示例:

// Struct inheriting Codable protocol
struct Food: Codable {
    var name: String
    var value: Double
}
struct Prediction: Codable {
    var foods: [Food]
    enum CodingKeys: String, CodingKey {
        case foods = "prediction"
    }
}

// SAMPLE DATA BEGIN, Use alamofire response instead
let string = """
{"prediction":[
{"name":"marshmallow","value":0.2800},
{"name":"caesar salad","value":0.0906},
{"name":"egg","value":0.0748},
{"name":"apple","value":0.0492},
{"name":"chickpea","value":0.0469}
]}
"""
let data = string.data(using: .utf8)!

用法:

let foods = try! JSONDecoder().decode(Prediction.self, from: string.data(using: .utf8)!).foods

print(foods[0].name)  // marshmallow
print(foods[0].value) // 0.28

注意:Codable 使 SwiftyJSON 作为解析器变得过时。

关于ios - 将 Alamofire POST 的 JSON 响应转换为可以显示的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49660273/

相关文章:

ios - 没有任何第三方支付处理器的Apple Pay沙盒环境测试

ios - Cocos2d游戏两个场景之间的ReplaceScene

javascript - 如何将 JavaScript 数组发送到 Rest 服务

swift - 如何更改 UIBarButtonItem 的字体样式和大小?

iOS8:扩展存储提供程序(导入、导出、移动)不起作用

c# - 如何统一生成JSON字符串?

python - Python 处理的输出的最佳数据结构是什么?

swift - 我的 Storyboard不是与屏幕边对边

ios - 更改窗口 Root View Controller 的效率如何?

ios - 类消息的接收者 SKViaPoint 是前向声明