json - 如何在 Swift 3 中用 Alamofire 4 解析这个 json?

标签 json swift alamofire

我有下面的 json,但无法弄清楚如何在 Swift 3 中解析它。我的代码在下面。来自 API 的 json 有一个数组根。我将 Xcode 8.2.1 与 Swift 4 和 Alamofire 4.0 一起使用。

["items": <__NSArrayM 0x608000248af0>(
{
    currency = USD;
    image = "https://cdn.myDomain.com/image.jpg";
    "item_title" = "Antique Table";
    "name:" = "";
    price = 675;
},
{
    currency = USD;
    image = "https://cdn.mydomain.com/image2.jpg";
    "name:" = "";
    price = 950;
...

这是我的代码。我试图从结果中获取数组 r 字典,但它始终为零。

Alamofire.request(myURL)
    .responseJSON(completionHandler: {
        response in
        self.parseData(JSONData: response.data!)
    })
}

func parseData(JSONData: Data) {

    do {
        let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.mutableContainers) as! [String: Any] 
        print(readableJSON)               
    }
    catch {
     print(error)
    }
}

我试过这个 let item = readableJSON["items"] as? [[String: Any]] 建议 here但它不会编译并出现错误 [String:Any] has no subscript and let item = readableJSON["items"] as? [String: Any]! 编译时带有警告 Expression implicited coerced from string 但生成 nil。解析这个 json 对我来说是生死攸关的事情。

最佳答案

做类似的事情

让 responseJSON = response.result.value 为! [字符串:AnyObject]

然后您将能够像这样访问该字典中的元素:

let infoElementString = responseJSON["infoElement"] as! String

关于json - 如何在 Swift 3 中用 Alamofire 4 解析这个 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41246491/

相关文章:

javascript - Ajv:使用动态键验证 json

用于检查错误标签的 JavaScript 正则表达式

Swift Toast 消息未显示 "UIApplication.sharedApplication().windows"

ios - 如何确保启动屏幕正在显示

ios - 如何从多维数组中过滤内部数组

javascript - 如何在 apache wicket 中加载 javascript 文件?

javascript - 未捕获( promise 中): Error: Error in ./搜索类搜索 - 内联模板:4:0 导致:超出最大调用堆栈大小

ios - NavigationController 标题不会出现 swift/storyboard

ios - 使用 Alamofire 上传图像时崩溃

json - 使用 Swift 2 的 Alamofire POST 请求