0

I need to decode a JSON to a dictionary. The json has String key and the values are strings or numbers.

   let decoder = JSONDecoder()
   let dict = try decoder.decode([String: Any].self, from: data)

This throws an exception about Any not being decodable. If I use [String : String] it trows an exception about finding a number when a string is expected.

How to do this right?

user426132
  • 1,341
  • 4
  • 13
  • 28

1 Answers1

1

Convert the any to model and decode it

struct Swifter: Decodable {
    let fullName: String
    let id: Int
    let twitter: URL
}

let json = """
    {
        "fullName": "Federico Zanetello",
        "id": 123456,
        "twitter": "http://twitter.com/zntfdr"
}
""".data(using: .utf8)! // our data in native (JSON) format
let myStruct = try JSONDecoder().decode(Swifter.self, from: json) // Decoding our data
print(myStruct) // decoded!!!!!

Or you can try this if you have son data

let responseDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87