2017-10-18 77 views
0
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]) 
     if let responseJSON = responseJSON as? [String:Any] { 
      if let tJsonObj = xResponse["d"] as? [[String:Any]] { 
       // not working here... 
      } 
     } 

tJsonObj變量未獲取我的json數組內容。 我的JSON是這樣的:Swift - 嵌套JSON中的分析數組對象不工作

{"d": "[{\"title\":\"xxx\",\"timestamp\":\"2017-10-16 23:53:40\"},{\"title\":\"Mein Test iPhone 7\",\"timestamp\":\"2017-10-17 18:16:24\"}]"} 

我希望有人能幫助 - 謝謝!

+0

看一看:https://stackoverflow.com/questions/41734982/parsing-nested-array-of-dictionaries-using-object-mapper/41735194#41735194 –

回答

1

d的值是另一個JSON字符串。您需要使用JSONSerialization兩次

do { 
    if let responseJSON = try JSONSerialization.jsonObject(with: data) as? [String:Any], 
    let tJsonObj = responseJSON["d"] as? String { 
     if let innerJSON = try JSONSerialization.jsonObject(with: Data(tJsonObj.utf8)) as? [[String:Any]] { 
      for item in innerJSON { 
       print(item) 
      } 
     } 
    } 
} catch { 
    print(error) 
} 
+0

非常感謝,這個解決方案很有效! – Neneil

0

d的內部JSON看起來沒有了。有效的JSON應如下所示:

{"d": "[{"title":"xxx","timestamp":"2017-10-16 23:53:40"},... 

您的JSON從哪裏來?

+0

的JSON來自我的服務器。對象是使用JavaScriptSerializer創建的。我確定JSON是有效的。 – Neneil