嗨,我得到服務器的回應,如下所示:
[
{
"success": {
"/lights/1/state/on": true
}
}
]
我想對其進行編碼怎么做?我嘗試了這樣的事情,但沒有奏效:
struct ResponseModel: Decodable {
var response: [ResponseDataModel]
struct ResponseDataModel: Decodable {
var status: [String: String]
}
}
let decodedResponse = try JSONDecoder().decode(ResponseModel.self, from: data)
print(decodedResponse)
uj5u.com熱心網友回復:
你的意思是解碼它。該屬性 is not responseshould be success,并且您收到的是陣列而不是字典。另請注意,您的字典值型別應該是 a Boolnot 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"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414899.html
標籤:
