简体   繁体   English

如何解码 swift 中的数组?

[英]How to decode an array in swift?

Hi I get response from server like so:嗨,我得到服务器的响应,如下所示:

[
    {
        "success": {
            "/lights/1/state/on": true
        }
    }
]

and I'd like to encode it how to do it?我想编码它怎么做? I try something like this but it didn't work:我尝试了这样的事情,但没有奏效:

struct ResponseModel: Decodable {
    
    var response: [ResponseDataModel]

    struct ResponseDataModel: Decodable {
        var status: [String: String]
    }
}

let decodedResponse = try JSONDecoder().decode(ResponseModel.self, from: data)
                        
print(decodedResponse)

You mean decode it.你的意思是解码它。 The property is not response should be success , and you are receiving an array not a dictionary.该属性不是response应该是success ,并且您收到的是数组而不是字典。 Note also your dictionary value type should be a Bool not a String :另请注意,您的字典值类型应该是Bool而不是String

let json = """
[
    {
        "success": {
            "/lights/1/state/on": true
        }
    }
]
"""

struct Response: Decodable {
    var success: [String: Bool]
}

let decodedResponse = try JSONDecoder().decode([Response].self, from: Data(json.utf8))
if let firstElement = decodedResponse.first {
    print(firstElement) // "Response(success: ["/lights/1/state/on": true])\n"
}

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

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