I want to encode a JSON that could be
{"hw1":{"get_trouble":true},"seq":2,"session_id":1}
or
{"hw2":{"get_trouble":true},"seq":3,"session_id":2}
the class for encoding looks like the following
class Request: Codable {
let sessionId, seq:Int
let content:[String:Content]
enum CodingKeys:String, CodingKey{
case sessionId = "session_id"
case seq
case content
}
init(sessionId:Int, seq:Int, content:[String:Content]) {
self.sessionId = sessionId
self.seq = seq
self.content = content
}
}
class Content:Codable{
let getTrouble = true
enum CodingKeys:String, CodingKey {
case getTrouble = "get_trouble"
}
}
how can I encode the request so that I can get the desired result? Currently, if I do
let request = Request(sessionId: session, seq: seq, content: [type:content])
let jsonData = try! encoder.encode(request)
I get
{"content":{"hw1":{"get_trouble":true}},"seq":2,"session_id":1}
and I don't want "content" inside the JSON. Already looked into
Swift Codable: encode structure with dynamic keys
and couldn't figure out how to apply in my use case