Another instance where the giant ant hits you with the curse of the evil JSONSerialization
. You have much more control on the serialisation process if you go the slightly more verbose way of the Codable
protocol, but the result will be much easier to handle. Put the following into a quick Playground to see the difference:
import Cocoa
let dictionary = ["nacho": ["1","2","3"]]
let jsonDt = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonDt!, encoding: .utf8)!
print(jsonString)
let jsonStr = "{\"nacho\":[\"1\",\"2\",\"3\"]}"
let jsonDat = jsonString.data(using: .utf8)
let dict = try? JSONSerialization.jsonObject(with: jsonDat!, options: .mutableLeaves)
print(dict!)
struct Chips: Codable {
let nacho: [Int]
}
let chip = Chips(nacho: [1, 2, 3])
print(chip)
let chipData: Data?
do {
chipData = try JSONEncoder().encode(chip)
print(String(data:chipData!, encoding:.utf8)!)
} catch {
print(error)
chipData = nil
}
if let chipData = chipData {
do {
let chips = try JSONDecoder().decode(Chips.self, from: chipData)
print(chips)
} catch {
print(error)
}
}
As you have seen the strings in the first serialisation/deserialization cycle end up being Ints
(which I suspect they should have been in the first place), even when they used to be String
. JSONSerialization.jsonObject
seems to have a mind of its own about which types you will be getting.
In my definition of Chips
(for lack of a better name) I could force the use of [Int]
which seems more clean. Try out the effect of changing this definition to String
. You will have to adapt the initialisation of the object and the serialised String
will of course reflect the change. The big advantage over your initial solution with JSONSerialization
consists in getting a consistent encode
/decode
cycle either way, of course with slightly different properties. Choose your preferred way and I am sure your Alamofire
will be happy to work with either.