I am currently trying to encode a generic struct (T) which has an attribute of this type with 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)
This results in a JSON like this:
{
"id" : 1,
"attribute" : {
"name" : "name",
"age" : 29
}
}
But i would like to customize the encoding to get the nested attributes to the root level:
{
"id" : 1,
"name" : "name",
"age" : 29
}
Using a custom CodingKey struct didn't work for me because T might have any number of attributes and the keys (names of attributes) are not known in advance.