我有多个要转换为 JSON 字符串的 Codeable 类。
class MyCodable: NSObject, Codable {
override init() {
}
func encode(to encoder: Encoder) throws {
}
}
class Category: MyCodable {
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self);
//... assign values and call super.init
}
override func encode(to encoder: Encoder) throws {
}
var categoyId: Int64;
var categoryName: String;
enum CodingKeys: String, CodingKey {
case categoryId
case categoryName
}
}
class Product: MyCodable {
required init(from decoder: Decoder) throws {
//..assign values and call super.init
}
override func encode(to encoder: Encoder) throws {
}
var productId: Int64;
var categoryId: Int64;
var productName: String;
enum CodingKeys: String, CodingKey {
case productId
case categoryId
case productName
}
}
我有一个用于转换的实用程序类。
class JSONUtil: NSObject {
public static func encode(objects: [MyCodable]) -> String {
var json: String = "";
do {
let encoder = JSONEncoder();
encoder.outputFormatting = .prettyPrinted;
let jsonData = try encoder.encode(objects);
json = String(data: jsonData, encoding: String.Encoding.utf8)!
} catch let convertError { json = "[{error: '" + convertError.localizedDescription + "'}]"; }
return json;
}
public static func toJson(object: MyCodable) -> String {
var objects = [MyCodable]();
objects.append(object);
return encode(objects: objects);
}
}
无论 MyCodable 对象数组中的内容是什么,返回值始终为“[{}]”。调试时,我可以看到 Category 对象的值已填充。
由于 MyCodable 没有属性,这就是 JSONEncoder 不打印 Category 属性的原因吗?.. 或者它为什么不打印 Category 属性?
我对 Product 对象有同样的问题。
目标是避免必须为我要打印到 JSON 的每个类自定义 JSON 转换。