我试图在swift 4中使用codable来解析自定义对象的提交数据,但仍然不确切知道。 这是我的自定义类:
class Response_Model : Codable {
var id : String?
var code : String?
enum CodingKeys: String, CodingKey {
case id = "id"
case code = "code"
}
init(){
id = ""
code = ""
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
code = try values.decodeIfPresent(String.self, forKey: .code)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(code, forKey: "code")
}}
在这里,我试图解析共鸣:
responseModel = try jsonDecoder.decode([Response_Model].self, from: result as! Data)
这是回应:
[
{
"id": "38",
"code": "code1"
},
{
"id": "39",
"code": "code2"
}]
谢谢
答案 0 :(得分:0)
您的代码过于繁琐,Codable
协议免费提供的大部分样板代码。
该课程可以简化为(顺便说一句,大多数情况下struct
就足够了)
struct ResponseModel : Codable {
var id : String
var code : String
}
现在解码JSON
let jsonString = """
[
{"id": "38", "code": "code1"},
{"id": "39", "code": "code2"}
]
"""
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode([ResponseModel].self, from: data)
for item in result {
print(item.code, item.id)
}
} catch { print(error) }