I use the new Codable protocol to turn a struct into a JSON and then into a dictionary for testing purposes. The problem is that the dictionary variable within the struct doesn't get converted back and stays Any rather than a [Int: String]
struct Person: Codable {
var name: String?
var history: [Int: String]
init() {
self.name = "Name"
history = [0: "Test"]
}
}
let person = Person()
let jsonData = try JSONEncoder().encode(person)
let result = try JSONSerialization.jsonObject(with: jsonData, options: [])
let dictionary = result as? [String: Any]
print(dictionary)
This gives me the following result
Optional(["history": {
0 = Test;
}, "name": Name])
When I would expect
Optional(["history":[0: "Test"]], "name": "Test"])
I would appreciate any explanation as to why this happens or, better yet, a solution how to basically do deep JSON serialization.
I am adding a playground demonstrating the problem: https://www.dropbox.com/s/igpntk7az0hevze/JSONSerialisation.playground.zip
[Int: String]is not an array, it's a dictionary and{0 = Test;}is how Swift formats a dictionary when you print it to the console for debugging... To me it seems like your code is working fine.let sampleDictionary: [String: Any] = ["history":[0: "Test"], "name": "Test"]and then print itprint(sampleDictionary), the result is["history": [0: "Test"], "name": "Test"]. And if I try to access history by usinglet history = dictionary["history"] as? [Int: String], the value is nil because it is not a dictionary.