Want to encode an object into a custom structure using JSONEncoder+Encodable.
struct Foo: Encodable {
var name: String?
var bars: [Bar]?
}
struct Bar: Encodable {
var name: String?
var value: String?
}
let bar1 = Bar(name: "bar1", value: "barvalue1")
let bar2 = Bar(name: "bar2", value: "barvalue2")
let foo = Foo(name: "foovalue", bars: [bar1, bar2])
Default approach of encoding foo gives:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(foo)
print(String(data: data, encoding: .utf8)!)
Output:
{
"name": "foovalue",
"bars": [
{
"name": "bar1",
"value": "barvalue1"
},
{
"name": "bar2",
"value": "barvalue2"
}
]
}
In the custom output I'd like to use the value of property name as the key, and the values of rest as the value for the mentioned key. The same will be applicable for nested objects. So I'd expect the output to be:
{
"foovalue": [
{
"bar1": "barvalue1"
},
{
"bar2": "barvalue2"
}
]
}
Question is whether Encodable/JSONEncoder supports this. Right now I just process the the first output dictionary and restructure it by iterating the keys.
Bar'sfunc encode(to:)method and creating your ownCodingKeys. However, this format can be somewhat ambiguous — why are you looking to do it this way? What if you need to add further properties in the future?Foo(name: "foo", bars: [bar1, bar2])encode(to:)you can defineCodingKeys however you need to and use them however you like — in this case you can define a struct which conforms toCodingKeyand can take on anyStringvalue