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)
CodePudding user response:
You mean decode it. The property is not response should be success, and you are receiving an array not a dictionary. Note also your dictionary value type should be a Bool not a 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"
}
