iOS Swift使用奇怪的格式将JSON响应转换为字典

时间:2017-10-18 17:20:33

标签: ios json swift

我正在尝试将swift中的JSON响应转换为可用的字典。这似乎是一个简单的任务,但是我得到的JSON响应格式奇怪,无论我尝试什么,我都无法将其转换为字典。我能够找到的所有谷歌示例都假设JSON响应的格式如下:

    {
    "someKey": 42.0,
    "anotherKey": {
        "someNestedKey": true
    },
    {
    "someKey": 42.0,
    "anotherKey": {
        "someNestedKey": true
    }

但是,我使用下面的代码收到的swift中的打印响应格式如下:

{assets = (
    {
    "someKey": 42.0,
    "anotherKey": {
        "someNestedKey": true
    },
    {
    "someKey": 42.0,
    "anotherKey": {
        "someNestedKey": true
    }
);
}

据我所知,尝试将此数据转换为swift中的字典。它将“assets”添加为字典中的单个键,该键的值是响应的其余部分。

    let url = URL(string: "https://\(apiKey):\(password)@\(yourStore).myshopify.com/admin/themes/\(currentThemeID)/assets.json")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error != nil {
        print(error)
    } else {
        if let urlContent = data {
            do {

                let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: [.allowFragments, JSONSerialization.ReadingOptions.mutableContainers])
                print(jsonResult)
                if let dictionary = jsonResult as? [String: [String]] {
                    print(dictionary)
                }

            } catch {
                print("json processing failed")
            }
        }
    }
}
task.resume()

我很确定挂断是在JSON响应中存在两个“括号”和“分号”。我无法找到任何关于这些字符如何影响响​​应的文档,或者在尝试使用swift进行向下转换时如何处理它们的文档。

任何帮助将不胜感激!

编辑: 我在浏览器中提取了JSON响应,这是格式化:

{"assets":[{"key":"assets\/1-1.png","public_url":"https:\/\/cdn.shopify.com\/s\/files\/1\/0810\/2125\/t\/22\/assets\/1-1.png?5272098227851596200","created_at":"2016-05-16T16:58:27-05:00","updated_at":"2016-05-16T16:58:27-05:00","content_type":"image\/png","size":9127,"theme_id":124078279}{"key":"templates\/search.liquid","public_url":null,"created_at":"2016-05-16T16:59:04-05:00","updated_at":"2016-05-16T16:59:04-05:00","content_type":"text\/x-liquid","size":2931,"theme_id":124078279}]}

此JSON响应没有assets =();其中的部分,并正确格式化。不知怎的,我的快速代码是不正确地解析数据?

1 个答案:

答案 0 :(得分:1)

反复强制转换为[String:Any]以获得所需的JSON响应部分。

    do {
        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: [.allowFragments, JSONSerialization.ReadingOptions.mutableContainers])
        print(jsonResult)
        guard
            let dictionary = jsonResult as? [String: Any],
            let assetData = dictionary["assets"] as? [String: Any] else {
                print("The JSON structure doesn't meet our expectations \(urlContent)")
                return
        }
        print(assetData)
    } catch {
        print("json processing failed")
    }