My company's API is.... unique. The only thing that is 100% is that all responses are encapsulated in a myCompany object. And then either in a Data object or an Errors object. After that it's pretty much fair game. I am working with our head API developer, but it's a slow change because the code was written 10 years ago etc.. etc..
{ "myCompany": {
"Errors": [{
//Various error message key/values based upon who ever created it
}]
}
}
{ "myCompany": {
"Data": {
//any key/value of arrays and objects that I want to turn into a Codable
}
}
}
Is there a way for me to test if a root level key exists before I try to JSON Decode into a Codeable Struct? I hope that makes sense.
For example if the json data has the root level key of jsonData["myCompany"]["Data"]
and MySpecialClass is what requested it, I could just send the value of jsonData["myCompany"]["Data"]
to MySpecialClass so it can json decode
let mydata = try? JSONDecoder().decode(MySpecialClassData.self, from: jsonData["myCompany"]["Data"])
It use to be in Objective-C I could just test for the keys in a dictionary to accomplish this. I don't know to this in Swift yet.
do {
guard let jsonData = try JSONSerialization.jsonObject(with: urlSessionDataTaskResponse, options: [.allowFragments]) as? [[String:Any]] else {
print("Error jsonData was not in the correct format. Surprise. Surprise.");
if let str = String(data: dataResponse, encoding: String.Encoding.utf8) {
print("Raw Data: \(str)")
}
return
}
// Something like this
// if jsonData["myCompany"]["Data"]
// else if jsonData["myCompany"]["Errors"]
// else who knows throw an error
///I have tried But this doesn't seem to work
guard let myCompany = jsonData["myCompany"] as? [String:Any] else { return }
} catch {
print("ERROR: \(error)")
}
All of the tutorials I have seen require me to put the data into a Codable before doing any.
Any thoughts?