如何使用 json 解码器解析嵌套的 json
how to parse nested json with jsondecoder
code = 200;
msg = "Verification_OTP";
result = {
"customer_email" = "ghg@Gmail.com";
"customer_name" = we;
"customer_phone" = 1234567890;
otp = 658715;
"user_id" = 135;
};
我无法解析我在 response.Here 中得到了 nil 是我的代码
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"
}
}
更改枚举大小写并检查 customer_phone 类型我认为它应该是 Int :
case customerMobile = "customer_phone"
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)
}
code = 200;
msg = "Verification_OTP";
result = {
"customer_email" = "ghg@Gmail.com";
"customer_name" = we;
"customer_phone" = 1234567890;
otp = 658715;
"user_id" = 135;
};
我无法解析我在 response.Here 中得到了 nil 是我的代码
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"
}
}
更改枚举大小写并检查 customer_phone 类型我认为它应该是 Int :
case customerMobile = "customer_phone"
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)
}