简体   繁体   中英

Parsing JSON with Codable, swift 4

I am using Swift 4 and Codables to parse JSON.

Following is my JSON:

{
    "data": {
        "email": "testuser14324@testuser.com",
        "cityUserId": 38,        
        "CityUser": {
            "isEmailVerified": false,
            "UserId": 711
        },
        "tokenInfo": {
            "accessToken": "eyJsds"
        }
    },
    "error": false
}

Following is the Model I am using

struct RootClass : Codable {
    let data : Data?
    let error : Bool?
}

For Data:

struct Data : Codable {

    let cityUser : CityUser?
    let cityUserId : Int?
    let email : String?
    let tokenInfo : TokenInfo?
}

For CityUser :

struct CityUser : Codable {

    let userId : Int?
    let isEmailVerified : Bool?

    enum CodingKeys: String, CodingKey {
        case userId = "UserId"
        case isEmailVerified = "isEmailVerified"
    }
}

For Token :

struct TokenInfo : Codable {

    let accessToken : String?
}

Decoding it as :

 let response = try JSONDecoder().decode(RootClass.self, from: resJson as! Data)

Problem :

response.data?.email = testuser14324@testuser.com
response.data?.tokenInfo?.accessToken = eyJsds
response.data?.cityUser = nil

It is returning correct email, cityUserId, tokenInfo.accessToken but it is returning "nil" for "CityUser". What shall I do?

That's the big disadvantage of declaring everything as optional. You get nil but you have no idea, why 😉.

It's just a typo: The property must match the spelling of the key (starting with capital letter in this case)

let CityUser : CityUser?

However to conform to the Swift naming convention it's recommended to use CodingKeys to transform uppercase to lowercase and if necessary snake_case to camelCase . By the way, Data is a struct in the Foundation framework in Swift 3+, use another name for example

struct ProfileData : Codable {

    let cityUser : CityUser
    let cityUserId : Int
    let email : String
    let tokenInfo : TokenInfo

    private enum CodingKeys: String, CodingKey {
        case cityUser = "CityUser"
        case cityUserId, email, tokenInfo
    }
}

maybe this is what you are looking for, app.quicktype.io what I use for parsing if I want to parse through codables. Ofcourse you can write and edit model provided from above tool by yourself too 😇 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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