简体   繁体   English

数组中可快速编码的不同键

[英]swift codable different key in array

I just used Swift 4 Codable to decode my json data from device. 我只是使用Swift 4 Codable从设备解码我的json数据。 I got a JSON data like below 我得到了如下的JSON数据

{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}

And I use Swift 4 我使用Swift 4

    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var CmdEnd: Bool
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]
        var DevSubItem: [DevSubItemList]
    }
    struct DevActionList: Codable{
        var DevMac: String
        var DevName: String
        var DevType: Int
        var DevProtocol: Int
        var ActionIdx: Int
        var Value: Int
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int,
        var Cmdset: Int,
        var SubStatus: String
    }
    let decoder = JSONDecoder()
    if receiveData.contains("DevListUpdate"){
        let data = receiveData.data(using: .utf8)!
        do {
            let locList = try JSONDecoder().decode(DevResults.self, from: data)
            print(locList)
        } catch let error {
            print(error)
        }
    }

}

But I cannot the correct JSON format because there are different key in DevItem Array. 但是我无法使用正确的JSON格式,因为DevItem数组中有不同的键。 And I tried to use var DevItem: Array<Dictionary<String: AnyObject>> 而且我尝试使用var DevItem: Array<Dictionary<String: AnyObject>>

Is there any solution for different key-value JSON file? 对于不同的键值JSON文件有什么解决方案吗?

Couple of things you missing - 您缺少的几件事-

  • You should make DevSubItem & DevAction properties as Optional 您应该将DevSubItemDevAction属性设置为Optional
  • You need to implement init(from decoder: Decoder) throws for decoding your JSON 您需要实现init(from decoder: Decoder) throws以解码JSON

Improved your code - 改善了您的代码-

     let jsonExample2 = """
{
    "CmdBegin": true,
    "GatewayMac": "1",
    "CmdName": "DevListUpdate",
    "DevItem": [
        {
            "DevMac": "00000000000000B0",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "A",
                    "Value": -1000
                },
                {
                    "DevName": "B",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00000000000000B1",
            "DevName": "Software Button",
            "DevAction": [
                {
                    "DevName": "C",
                    "Value": -1000
                },
                {
                    "DevName": "D",
                    "Value": -1000
                }
            ]
        },
        {
            "DevMac": "00:17:88:01:00:fa:2a:5d-0b",
            "DevName": "E",
            "DevSubItem": [
                {
                    "SubIndex": 0,
                    "Cmdset": 0,
                    "SubStatus": "1"
                },
                {
                    "SubIndex": 1,
                    "Cmdset": 512,
                    "SubStatus": "14"
                }
            ]
        }
    ]
}

""".data(using: .utf8)!
    struct DevResults: Codable{
        var CmdBegin: Bool
        var GatewayMac: String
        var CmdName: String
        var DevItem: [DevList]
    }
    struct DevList: Codable {
        var DevMac: String
        var DevName: String
        var DevAction: [DevActionList]?
        var DevSubItem: [DevSubItemList]?
    }
    struct DevActionList: Codable{
        var DevName: String
        var Value: Int
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            DevName = try values.decode(String.self, forKey: .DevName)
            Value = try values.decode(Int.self, forKey: .Value)
        }
    }
    struct DevSubItemList: Codable{
        var SubIndex: Int
        var Cmdset: Int
        var SubStatus: String
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            SubIndex = try values.decode(Int.self, forKey: .SubIndex)
            Cmdset = try values.decode(Int.self, forKey: .Cmdset)
            SubStatus = try values.decode(String.self, forKey: .SubStatus)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        let jsonDecoder = JSONDecoder()
        do {
            let modelResult = try jsonDecoder.decode(DevResults.self,from: jsonExample2)
            if modelResult.DevItem.count > 0 {
                print("dev Name is \(modelResult.DevItem.first?.DevName ?? "-")")
            }

        } catch {
            print(error)
        }
    }
}

Apple docs - Using JSON with Custom Types you can also download sample code from apple on that link. Apple文档- 使用JSON与自定义类型,您还可以在该链接上从Apple下载示例代码。

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

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