0

I got a struct like the following

struct Wrapper {

  var value: [String: Any]
  // type "Any" could be String, Int or [String]. 
  // i.g. ["a": 1, "b": ["ccc"]]
  // and the keys of this dictionary are not determined 
}

I been struggled for quite a while😭. Anyone has any idea how to resolve it?

1
  • 1
    You can use enum types instead of Any but i think such missy json need a usual serialization not codable Commented Mar 30, 2021 at 11:46

1 Answer 1

2

You can use some library like AnyCodable

Then you can make your struct Codable by using AnyCodable class instead of Any.

struct Wrapper: Codable {
    var value: [String: AnyCodable]
}

Example

let arrayWrapper: [String: Any] =
["value" :
       [
         "test" : ["1", "2", "3"],
         "parse" : ["4", "5", "6"]]
        ]

let jsonData = try! JSONSerialization.data(withJSONObject: arrayWrapper, options: .prettyPrinted)

do {
   let decoder = JSONDecoder()
   let result = try decoder.decode(Wrapper.self, from: jsonData)
   print("result:", result)
} catch let error {
   print("error:", error)
}

Output

result: Wrapper(value: ["parse": AnyCodable(["4", "5", "6"]), "test": AnyCodable(["1", "2", "3"])])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.