Reputation: 105
I am using Swift 4 and Codables to parse JSON.
Following is my JSON:
{
"data": {
"email": "[email protected]",
"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 = [email protected]
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?
Upvotes: 1
Views: 1577
Reputation: 444
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 😇 .
Upvotes: 0
Reputation: 285220
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
}
}
Upvotes: 2