如何在Swift 4中解码JSON? [英] How to Decode JSON in Swift 4?

查看:113
本文介绍了如何在Swift 4中解码JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Swift 4解码以下json?

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
}

这给了我以下错误:

keyNotFound(LocalNotificationsAlert.Root.CodingKeys.id, Swift.DecodingError.Context(codingPath:[],debugDescription:否 与键ID(\"id \").相关联的值.,底层错误:nil))

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.

推荐答案

Root 对象不是具有idpackageIdpackage键的字典,即Root对象是具有键dataerrormessage的外部词典.

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.

所以您需要3个结构

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
}

这篇关于如何在Swift 4中解码JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆