I am new to swift and am trying to figureout passing Nested Json. So far I have tried JSONSerialization without success but after being advised to switch to Codable I have give it a try but I keep getting nill from parsed JSON. Code I have so far:
struct AppData: Codable {
let paymentMethods: [PaymentMethods]?
}
struct PaymentMethods: Codable {
let payment_method: String?
}
AF.request(startAppUrl, method: .post, parameters: requestParams , encoding: JSONEncoding.default).responseString{
response in
switch response.result {
case .success(let data):
let dataStr = data.data(using: .utf8)!
let parsedResult = try? JSONDecoder().decode( AppData.self, from: dataStr)
print(parsedResult)
case .failure(let error):
print((error.localizedDescription))
}
}
My JSON data can be found here: https://startv.co.tz/startvott/engine/jsonsample/ . I am using xcode 11
I will appreciate assistance as its already one week stuck on this.
Codableis that the data structure has to mirror the structure of the json data and, unless usingCodingkeysto remap fields, have the same field names as the json. You can use a custominit(with decoder:)to handle situations where there are anomalies, but in your case the data structure is not even close to the json layout.try?in aJSONDecoder()line. Never do that. Remove the question mark, add ado - catchblock and print theerrorinstance. Decoding errors are extremely descriptive.