I would like to represent a generic JSON object in Swift:
let foo: [String: Any] = [
"foo": 1,
"bar": "baz",
]
But the [String: Any]
type suggested by the compiler doesn’t really work well. I can’t check two instances of the type for equality, for example, while that should be possible with two JSON trees.
What also doesn’t work is using the Codable
machinery to encode that value into a JSON string:
let encoded = try JSONEncoder().encode(foo)
Which blows up with an error:
fatal error: Dictionary<String, Any> does not conform to Encodable because Any does not conform to Encodable.
I know I can introduce a precise type, but I am after a generic JSON structure. I even tried to introduce a specific type for generic JSON:
enum JSON {
case string(String)
case number(Float)
case object([String:JSON])
case array([JSON])
case bool(Bool)
case null
}
But when implementing Codable
for this enum I don’t know how to implement encode(to:)
, since a keyed container (for encoding objects) requires a particular CodingKey
argument and I don’t know how to get that.
Is it really not possible to create an Equatable
generic JSON tree and encode it using Codable
?