0

I want to parse JSON with Swift 4.1

I know this might look similar at first glance.

Now, Swift 4.1 and Codable gives us a great tool.

However how do I use it / parse it - when I don't know the structure???

Lets say my JSON can be

{ "foo" : "bar" }

and also

{ "foo" : { "baz" : "bar" }}

Or even as simple as

{ "foo" : 1 }

Then I can't use Codable right? Or did I totally get it wrong?

How to parse it then??

bnassler
  • 591
  • 6
  • 15
  • Is this a real situation? – matt Apr 24 '18 at 14:29
  • Yes. I want to consume data from an API which gives me that. In reality it will only nest up to, lets say 10 levels but still... I am trying to find a reasonably elegant solution but I can't... – bnassler Apr 24 '18 at 14:31
  • So you can just test: can we decode as string? No? Can we decode as Int? Etc. or define a Decodable type StringOrIntOrWhatever. – matt Apr 24 '18 at 14:36
  • 1
    Codable is for "type-safe" APIs. Its job is to deserialize json into Swift objects. Since your server responses are totally random, you should go for Ahsley Mills answer – heyfrank Apr 24 '18 at 14:37
  • I did (for more than 5 minutes I promise...) didn't come up but that was what I was looking for. Its still "not very nice" but I buy the type safety. – bnassler Apr 24 '18 at 14:49
  • @matt Unfortunately that link is about JSON that conforms to specific types but the question is about arbitrary JSON. Other "duplicates" you've posted have the same problem. Please check the text before posting "duplicates". –  Mar 15 '22 at 22:34

1 Answers1

-1

It sounds like you want to turn your JSON data into Dictionaries and Arrays - in which case…

do {
    if let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
       // Do something with your dict
    }
} catch {
    print("Error deserializing: \(error)")
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160