0
我試圖將一個JSON響應迅速轉換爲一個可用的字典。這似乎是一個簡單的任務,但是我得到的JSON響應格式很奇怪,無論我嘗試什麼,我都無法將它轉換爲字典。所有的谷歌的例子,我已經能夠找到假定JSON響應的格式如下:iOS Swift Casting JSON響應與奇怪的格式到字典
{
"someKey": 42.0,
"anotherKey": {
"someNestedKey": true
},
{
"someKey": 42.0,
"anotherKey": {
"someNestedKey": true
}
然而,在迅速我用下面的格式爲代碼在接收到打印響應如下:
{assets = (
{
"someKey": 42.0,
"anotherKey": {
"someNestedKey": true
},
{
"someKey": 42.0,
"anotherKey": {
"someNestedKey": true
}
);
}
這是盡我所能試圖將這些數據轉換成字典在迅速。它將「資產」添加爲字典中的單個關鍵字,該關鍵字的值就是整個響應的其餘部分。
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響應中兩個「括號」和「分號」的存在。我無法找到任何有關這些角色如何影響響應的文檔,或者在嘗試快速下調時如何處理它們。
任何幫助,將不勝感激!
編輯: 我拉起我的瀏覽器中的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響應不具有資產=();部分,並且格式正確。不知何故,我的swift代碼不正確地解析數據?
這個響應是'print(jsonResult)'的結果還是你得到的實際響應數據?這是無效的json – dan
@dan我在瀏覽器中提出了響應,並且在那裏格式正確。我在上面的問題編輯中發佈了snippit。這告訴我這個問題存在於我的Swift代碼中,以及它如何解析數據? –
要回答你的問題@dan,它是在swift中打印的結果,而不是實際的json響應。 –