在JSON中使用nil而不是Optional(<null>)作为null值

Eth*_*han 11 json swift

在斯威夫特,NSJSONSerialization.JSONObjectWithData使用Optional(<null>)null在JSON值.是否可以告诉解析使用nil(即删除带有null值的字段,因为Swift Dictionary不允许nil值)?

Dar*_*uin 16

Optional()是一个NSNull值.你可以避免这样的错误:

if !(myField is NSNull) {
    //Whatever you want to do with myField when not null
} else {
    //Whatever you want to do when myField is null
}
Run Code Online (Sandbox Code Playgroud)


jtb*_*des 13

NSJSONSerialization使用NSNull对象,这就是你所看到的; 你可以通过比较来检查它们NSNull().

  • 那很难看.我有一个大的json对象,其值可以是字符串或null.因此,不是将整个事物转换为`[String:String]`,而是必须使用`[String:AnyObject]`,每当我需要访问一个字段时,我必须写一些像`value =(dict [" field1"] == nil || dict ["field1"]是NSNull)?nil:(dict ["field1"]!as String)`而不仅仅是`value = dict ["field1"]` (2认同)
  • @Ethan 在解析时,如果您知道可以有 `nil` 值,则转换为 `[String: String]` 永远不会安全。当属性可以作为属性而不是字符串键访问时,最好将字段单独解析到您的自定义结构/类中。此外,简单的类型安全模式是 `value = dict["field1"] as? String`,你不必专门检查 `NSNull`。检查您想要的类型。 (2认同)