问题描述
我目前正在尝试使用T
对具有这种类型属性的通用结构(JSONEncoder
)进行编码:
struct A <T:Codable> : Codable {
var id: Int
var attribute : T
init(id: Int,attribute: T){
self.id = id
self.attribute = attribute
}
}
struct B : Codable {
var name: String
var age: Int
}
let encoder = JSONEncoder()
let foo = A<B>(id: 1,attribute: B(name: "name",age: 29))
try? encoder.encode(foo)
这将导致如下所示的JSON:
{
"id" : 1,"attribute" : {
"name" : "name","age" : 29
}
}
但是我想自定义编码以使嵌套属性达到根级别:
{
"id" : 1,"name" : "name","age" : 29
}
使用自定义CodingKey
结构对我不起作用,因为T
可能具有任意数量的属性,并且键(属性名称)事先未知。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)