簡體   English   中英

數組中可快速編碼的不同鍵

[英]swift codable different key in array

我只是使用Swift 4 Codable從設備解碼我的json數據。 我得到了如下的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"
                }
            ]
        }
    ]
}

我使用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)
        }
    }

}

但是我無法使用正確的JSON格式,因為DevItem數組中有不同的鍵。 而且我嘗試使用var DevItem: Array<Dictionary<String: AnyObject>>

對於不同的鍵值JSON文件有什么解決方案嗎?

您缺少的幾件事-

  • 您應該將DevSubItemDevAction屬性設置為Optional
  • 您需要實現init(from decoder: Decoder) throws以解碼JSON

改善了您的代碼-

     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文檔- 使用JSON與自定義類型,您還可以在該鏈接上從Apple下載示例代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM