我有一堂课,它有下一个
import UIKit
final class PruebaModel: Codable {
let a: String?
let b: String?
let c: [D]?
let f: String?
enum CodingKeys: String, CodingKey {
case a = "a"
case b = "b"
case c = "c"
case f = "f"
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
a = try values.decodeIfPresent(String.self, forKey: .a)
b = try values.decodeIfPresent(String.self, forKey: .b)
c = try values.decodeIfPresent([D].self, forKey: .c)
f = try values.decodeIfPresent(String.self, forKey: .f)
}
required init() {
a = ""
b = ""
c = Array<D>()
f = ""
}
}
import Foundation
struct D: Codable {
let l: String
let m: String
enum CodingKeys: String, CodingKey {
case l = "l"
case m = "m"
}
init(from decoder: Decoder) throws {
let value = try decoder.container(keyedBy: CodingKeys.self)
l = try value.decode(String.self, forKey: .l)
m = try value.decode(String.self, forKey: .m)
}
public func encode(to encoder: Encoder) throws {
//Implement when needed
}
}
json是下一个
{
"a": "a",
"b": "b",
"c": [
{
"l": "¿Cuál es el mi color favorito?",
"m":"QAUY.15"
}
],
"f": "f"
}
该类是完美的,它具有带参数的对象,但是当我尝试将类转换为 json 时。数组为空
代码
let jsonData = try! JSONEncoder().encode(PruebaModel)
let jsonString = String(data: jsonData, encoding: .utf8)!
我评估表达式时的结果
po String(data: try! JSONEncoder().encode(PruebaModel), encoding: .utf8)!
"{"a":"a","b":"b","c":[{}],"f":"f"}"
为什么 c 是空的?它在数组中有一个对象。
如果对象在数组中没有特殊字符,则解码显示该对象