как разобрать вложенный json с помощью jsondecoder - PullRequest
0 голосов
/ 11 июня 2019
code = 200;
msg = "Verification_OTP";
result =     {
    "customer_email" = "ghg@Gmail.com";
    "customer_name" = we;
    "customer_phone" = 1234567890;
    otp = 658715;
    "user_id" = 135;
};

Я не могу разобрать, я получил ноль в ответ. Вот мой код

struct Root: Codable {
let code: Int?
let msg: String?
let customerModel: Result?
}
struct Result: Codable {
    let customerName:String?
    let customerEmail:String?
    let customerMobile:String?
    let otp:Int?
    let userId:Int?
    enum CodingKeys: String ,CodingKey {
        case customerName = "customer_name"
        case customerEmail = "customer_email"
        case customerMobile = "customer_no"
        case userId = "user_id"
        case otp = "otp"
    }

}

Ответы [ 2 ]

2 голосов
/ 11 июня 2019

1. Если ваш JSON ответ такой:

{
    "code": 200,
    "msg": "Verification_OTP",
    "result": {
        "customer_email": "ghg@Gmail.com",
        "customer_name": "we",
        "customer_phone": 1234567890,
        "otp": 658715,
        "user_id": 135
    }
}

2. Ваши Codable модели будут выглядеть так:

struct Response: Codable {
    let code: Int
    let msg: String
    let result: Result
}

struct Result: Codable {
    let customerEmail: String
    let customerName: String
    let customerPhone: Int
    let otp: Int
    let userId: Int
}

3. Разобрать data с вышеуказанными моделями, такими как:

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let response = try decoder.decode(Response.self, from: data)
    print(response)
} catch {
    print(error)
}
0 голосов
/ 11 июня 2019

Измените регистр enum, а также проверьте тип customer_phone, я думаю, это должно быть Int:

case customerMobile = "customer_phone"
...