首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将JSON响应从Alamofire POST转换为可显示的变量

将JSON响应从Alamofire POST转换为可显示的变量
EN

Stack Overflow用户
提问于 2018-04-05 04:55:16
回答 2查看 239关注 0票数 0

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

代码语言:javascript
复制
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上尝试了几次,

如下所示:

代码语言:javascript
复制
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’类型的值加上下标。

那么,有人愿意帮我这个忙吗?提前感谢

EN

回答 2

Stack Overflow用户

发布于 2018-04-05 05:39:35

Alamofire不会自动解析response.result.value (值仍然是序列化的JSON字符串)。既然您提到了SwiftyJSON,请尝试使用SwiftyJSON的JSON(jsonString)函数解析该值。

代码语言:javascript
复制
/** 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)")
}

我不确定这是唯一的问题,但这是一个开始。

票数 0
EN

Stack Overflow用户

发布于 2018-04-05 05:40:04

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

代码语言:javascript
复制
// 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)!

用法:

代码语言:javascript
复制
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作为解析器变得过时。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49660273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档