Skip to content

IOS dictionary serialization issue

Carlos César Neves Enumo edited this page Apr 9, 2020 · 1 revision

If you have a non-serializable object in your dictionary you can use this code:

// Date object example
func encodableDict(_ dict: [String: Any]) -> [String: Any] {
    return dict.mapValues { (value) -> Any in
        if value is Date {
            // serialize Date manually
            return "\(value)"
        } else if let value = value as? [String: Any] {
            return encodableDict(value)
        }
        return value
    }
}
JSONSerialization.data(withJSONObject: encodableDict(dict))
Clone this wiki locally