How to Decode JSON in Swift 4?

五迷三道 提交于 2020-01-06 06:47:06

问题


How to decode following json using Swift 4?

{
    "data": {
        "id": 22,
        "packageId": 5,
        "Package": {
            "id": 5,
            "color": "blue"
        }
    },
    "error": false,
    "message": "Successfully Fetched"
}

I have tried it using following:

struct Root: Codable {

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case packageId = "packageId"
        case package = "Package"
    }

    var package : Package
    var id : Int
    var packageId : Int
}

struct Package : Codable {
    var id : Int
    var color : String
}

It is giving me following error:

keyNotFound(LocalNotificationsAlert.Root.CodingKeys.id, Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key id (\"id\").", underlyingError: nil))

Please help me in fixing this, Thank you.


回答1:


The Root object is not the dictionary with id, packageId and package keys, the Root object is the outer dictionary with keys data, error, message.

So you need 3 structs

struct Root: Codable {
    let data : PackageData? // If `error` is true `data` might be missing
    let error : Bool
    let message : String
}

struct PackageData: Codable {

    enum CodingKeys: String, CodingKey {
        case package = "Package"
        case id, packageId
    }

    let package : Package
    let id : Int
    let packageId : Int
}

struct Package : Codable {
    let id : Int
    let color : String
}



回答2:


If you don't want to custom decode the response, you would need to provide the struct for the entire json response.

struct Response: Decodable {
    let data: Root
    let error: Bool
    let message: String
}


来源:https://stackoverflow.com/questions/48161748/how-to-decode-json-in-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!