简体   繁体   English

Swift 可编码/可使用嵌套 json 阵列解码

[英]Swift Codable / Decodable with Nested json Array

I am new to swift and am trying to figureout passing Nested Json.我是 swift 的新手,我正在尝试通过嵌套 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.到目前为止,我已经尝试过 JSONSerialization,但没有成功,但在被建议切换到 Codable 之后,我试了一下,但我一直从解析的 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/ .我的 JSON 数据可以在这里找到: https://startv.co.tz/startvott/engine/jsonsample/ I am using xcode 11我正在使用 xcode 11

I will appreciate assistance as its already one week stuck on this.我将感谢您的帮助,因为它已经坚持了一周。

First of all replace responseString with responseData in the request line, this avoids the extra step to convert string (back) to data.首先在请求行中将responseString替换为responseData ,这样可以避免将字符串(返回)转换为数据的额外步骤。

Second of all add always a do - catch block around a JSONDecoder line.其次,始终在JSONDecoder行周围添加一个do - catch块。 Never ignore decoding errors with try?永远不要忽略try? . . The block will catch this comprehensive DecodingError :该块将捕获这个全面的DecodingError

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "paymentMethods", intValue: nil)], debugDescription: "Expected to decode Array but found a string/data instead.", underlyingError: nil)) typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "paymentMethods", intValue: nil)], debugDescription: "期望解码 Array 但找到了一个字符串/数据。",底层错误: nil) )

The error states that the value for key paymentMethods is not an array.该错误表明键paymentMethods的值不是数组。 It's a string.这是一个字符串。 Looking at the JSON it's in fact a nested JSON string which must be decoded on a second level.查看 JSON 它实际上是一个嵌套的 JSON 字符串,必须在第二级解码。

struct AppData: Codable {
    let paymentMethods: String
}
struct PaymentMethods: Codable {
    let paymentMethod: String
}

AF.request(startAppUrl, method: .post, parameters: requestParams , encoding: JSONEncoding.default).responseData{
    response in
    switch response.result {
        case .success(let data):
            do {
                let parsedResult = try JSONDecoder().decode( AppData.self, from: data)
                let paymentData = Data(parsedResult.paymentMethods.utf8)
                let secondDecoder = JSONDecoder()
                secondDecoder.keyDecodingStrategy = .convertFromSnakeCase
                let paymentMethods = try secondDecoder.decode([PaymentMethods].self, from: paymentData)
                print(paymentMethods)
            } catch {
                print(error)
            }

        case .failure(let error):
            print((error.localizedDescription))
    }
}

Side note:边注:

The URL doesn't require a POST request and parameters. URL 不需要 POST 请求和参数。 You can omit all parameters except the first.您可以省略除第一个参数之外的所有参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM