0

What must be a rookie JSON/learning parsing error on my part: I expected my website of interest's json feed to return an array-of-dicionaries. I naively assumed if there was only a single entry, it would be a array with a single dictionary.

Doh! In the case where there is only a single dictionary to return, the api drops the array brackets and simply gives a dictionary. I'll confess to only lightly digging around for a JSON spec, but now I gather this is standard.

Perhaps this is a "best practices" question and perhaps it cannot be improved upon (cleaner? more elegant?)... but I am curious if in Swift 3 there is a nicer way to handle this array OR dictionary parse. Currently I am parsing it as follow:

if let record = json["record"] as? [[String : Any]] {
  // Parse record as an array of dictionaries
} else if let record = json["record"] as? [String : Any] {
  // Parse record as a dictionary
}
Electro-Bunny
  • 1,380
  • 2
  • 12
  • 33
  • With Swift 3 this is the right way. With Swift 4 you might be interested in looking at JSONDecoder (but the solution won't be simpler, just different). – Eric Aya Dec 10 '17 at 18:09
  • @Moritz if you promote your comment to an answer I will give you the collar. – Electro-Bunny Dec 10 '17 at 22:13
  • Actually for Swift 4 I don't like the JSONDecoder solutions that I know of, like in https://stackoverflow.com/a/46049763/2227743 for example; and posting an answer just saying that your Swift 3 way is ok, without demonstrations or explanations, seems a bit weak to me. So I prefer to let someone else post an answer with details. ;) – Eric Aya Dec 11 '17 at 10:13

0 Answers0