简体   繁体   English

使用Codable快速解析JSON 4

[英]Parsing JSON with Codable, swift 4

I am using Swift 4 and Codables to parse JSON. 我正在使用Swift 4和Codables解析JSON。

Following is my JSON: 以下是我的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 : 对于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". 它返回正确的电子邮件,cityUserId,tokenInfo.accessToken,但返回“ nil”作为“ CityUser”。 What shall I do? 我该怎么办?

That's the big disadvantage of declaring everything as optional. 这就是将所有内容都声明为可选项的最大缺点。 You get nil but you have no idea, why 😉. 你得到nil但你不知道为什么,😉。

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 . 但是,为了符合Swift命名约定,建议使用CodingKeys将大写转换为小写,并在必要时将snake_case转换camelCase By the way, Data is a struct in the Foundation framework in Swift 3+, use another name for example 顺便说一句, Data是Swift 3+中Foundation框架中的结构,例如使用另一个名称

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. 也许这就是您正在寻找的app.quicktype.io ,如果我想通过可编码对象进行解析,我将使用它进行解析。 Ofcourse you can write and edit model provided from above tool by yourself too 😇 . 当然,您也可以自己编写和编辑从上述工具提供的模型😇。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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