JSONEncoder with dictionary of objects?

I have a need to wrap several kinds of objects into a dictionary say [String: Any?], but how do I tell that the Any? object is all Encodable?

let params: [String: Any?] = ["num": 123, "text": "abc", "obj": encodableobject]

JSONEncoder().encode(params) // compiler error because Any? is not Encodable
Answered by Claude31 in 762753022

You just cannot.

What I do in such a case

  • create an intermediate struct, Codable, with the different properties
  • "num": Int, "text": String, "obj": Encodableobject
  • convert the dict to such an object
  • Now I can encode as JSON and decode and rebuild dictionary

If that may help :

Accepted Answer

You just cannot.

What I do in such a case

  • create an intermediate struct, Codable, with the different properties
  • "num": Int, "text": String, "obj": Encodableobject
  • convert the dict to such an object
  • Now I can encode as JSON and decode and rebuild dictionary

If that may help :

JSONEncoder with dictionary of objects?
 
 
Q