如何使用jsondecoder解析嵌套的json

时间:2019-06-11 12:01:35

标签: swift jsondecoder

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 个答案:

答案 0 :(得分:2)

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)
}

答案 1 :(得分:0)

更改枚举大小写并检查我认为应该为Int的customer_phone类型:

case customerMobile = "customer_phone"