0

I've a dictionary with optional values:

let user = [
  "name": "gui",
  "username": nil,
] as [String: Any?]

that I simply want to cast to a json that should be {"name": "gui", username: null}

However, JSONSerialization.isValidJSONObject(user) returns false, and try JSONSerialization.data(withJSONObject: user) fails..

How should I handle that?

Guig
  • 9,891
  • 7
  • 64
  • 126
  • if there is no user name then put empty string as username instead of nil – Shankar BS Aug 30 '16 at 07:47
  • JSSONSerialization cannot handle optionals. You have to use `NSNull()`, which is mapped to `null` in the JSON data. – Martin R Aug 30 '16 at 07:55
  • @Shan I disagree, there's quite a difference between null and "", or between null and 0 – Guig Aug 30 '16 at 08:11
  • @MartinR that seems to work but it's very annoying because an optional `MyClass?` cannot be set to `NSNull()` Is there no better option? What the duplicated question I could not found? – Guig Aug 30 '16 at 08:16
  • JSONSerialization handles only a limited set of types: dictionaries, arrays, strings, dates, numbers, nulls, but not custom classes. – The duplicate appears now at the top of your question. – Martin R Aug 30 '16 at 08:32

0 Answers0