【发布时间】:2021-02-03 18:47:39
【问题描述】:
我有一门课,它有下一个
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 是空的?它在数组中有一个对象。
如果数组中的对象没有特殊字符,则解码显示该对象
【问题讨论】:
-
但是不正确,因为对象D有数据。
-
我删除了之前的评论,因为您更新了问题...您要编码的实际对象是什么?
D.encode(to:)真的是空的吗? -
不,我尝试编码 PruebaModel
-
PruebaModel是一种类型,而不是实例。你是编码(从对象到 JSON)还是解码(从 JSON 到对象)? -
Object-to-JSON 被称为“编码”。如果你有一个对象
let pruebalModel = PruebalModel(....),那么你可以用JSONEncoder().encode(pruebalModel)对其进行编码,但是由于D.encode(to:)是空的,它会编码成一个空的JSON。你的代码JSONEncoder().encode(PruebalModel)甚至不应该编译
标签: json objective-c swift xcode jsonencoder