So working with JSON in Swift has me stumped! I’ve been trying like hell to create large JSON objects in Swift but keep running into the same problem: Not everything you can write in pure JSON can be re-written with Swift Dictionaries. The networking libary which I’m currently using, Alamofire, expects you to write your JSON using Swift Dictionaries, and then the library/wrapper converts everything into JSON for you before sending it over the network using the HTTP POST method.
However, I think I’ve figured out the missing work-around. Well actually… someone on StackOverflow has figured out the missing work-around: How to make HTTP Post request with JSON body in Swift
Now, not everything in the blog post is relevant to what I’m trying to do as they are working with URLSession instead of Alamofire to handle the networking. But, I noticed one very interesting thing in the answers section that leads me to believe I’ve found the missing work-around. Here is how one StackOverflow user wrote his JSON:
let json: [String: Any] = [ "title": "ABC", "dict": [ "1":"First", "2":"Second" ] ]
Notice, he uses numbers for keys (as I would like to do) and is able to get away with this by cleverly wrapping the numbers in quotes to create a string! Sort of a hacked-together work around, but I think this is what I’ve been missing! Now all I have to do is cast the indexes in my arrays of data as strings and I’m good to go! Looks like things are headed in the right direction 🙂