Looping through JSON object in Swift

孤者浪人 提交于 2020-12-31 14:56:40

问题


I got this JSON object which I sent from my server to my Swift application.

{
  "625289": {
    "id": 1,
    "subject": "Hello World"
  },
  "625277": {
    "id": 2,
    "subject":"Bye World!"
  }
}

So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:

struct Resultat : Decodable   {
  let subject: String
}

var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")

URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
  do {
    print("coucoulol")
    //print(response)

    self.result = try JSONDecoder().decode([Resultat].self, from: data!)

    print(self.result)

    for eachTicket in self.result {
      print(eachTicket.subject)
    }
  } catch {
    print("error"+error.localizedDescription)
  }
}.resume()

However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.


回答1:


The root object is a dictionary. You can decode the object to [String:Resultat]. The dictionary contains also dictionaries. An array is not involved.

struct Resultat : Decodable {
    let subject: String
    let id : Int
}

...
let result = try JSONDecoder().decode([String:Resultat].self, from: data!)
for (key, value) in result {
    print(key, value.subject)
}



回答2:


You can try using SwiftyJSON below

$0.0 = Key

$0.1 = value

let data = JSON(result)
data.dictionaryValue.forEach({
     print($0.1)
})


来源:https://stackoverflow.com/questions/47326354/looping-through-json-object-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!