gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:36:52 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com