简体   繁体   中英

Swift - Parse array in nested JSON Object not working

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...
            }
        }

The tJsonObj variable does not get my json array content. My json looks like this:

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

I hope someone can help - thanks!

The value for key d is another JSON string. You need to use JSONSerialization twice

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)
}

The inner JSON for d looks escaped. Valid JSON should look something like:

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

Where is your JSON coming from?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM