我正在使用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)
}以下是我得到的回复:

我的问题是,如何将名称和值保存为变量,以便在我的应用程序上显示它?我这样做,实际上我在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"]但是它给了我这样一个错误:不能用'String‘类型的索引给'String’类型的值加上下标。
那么,有人愿意帮我这个忙吗?提前感谢
发布于 2018-04-05 05:39:35
Alamofire不会自动解析response.result.value (值仍然是序列化的JSON字符串)。既然您提到了SwiftyJSON,请尝试使用SwiftyJSON的JSON(jsonString)函数解析该值。
/** Parse the string with SwiftyJSON */
let json = JSON(response.result.value)
let name = json["name"]
/** Parse Predictions arrayValue */
for row in json["predictions"].arrayValue {
let name = row["name"].string
let value = row["value"].double
print("Prediction for \(name) is \(value)")
}我不确定这是唯一的问题,但这是一个开始。
发布于 2018-04-05 05:40:04
以下是在Swift 4中使用Codable协议进行原生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作为解析器变得过时。
https://stackoverflow.com/questions/49660273
复制相似问题