从JSON处理空值

时间:2018-10-13 18:17:06

标签: ios json swift

我正在尝试调用一个API,该API给我一个JSON响应,该响应通过使用JSON解码器和可解码结构进行解析。

例如,JSON数据为:

{
 "value":[
  {
   "name":abc
  },
  {
   "name":null
  }
 ]
}

结构是这样的:

struct output: Decodable {
    let value: [value]

    enum CodingKeys: String, CodingKey {
        case value = "value"
    }
}

struct value: Decodable {
    let name: String

    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
}

我不确定获得空值时如何处理此情况,因为 解码器给出了序列化JSON的错误。

1 个答案:

答案 0 :(得分:1)

替换

let name: String

使用

let name: String?

{
 "value":[
  {
   "name":"abc"
  },
  {
   "name":null
  }
 ]
}

如果键相同,也不需要CodingKeys

struct Output: Decodable { // start structs with capital letter 
    let value: [Value] 
}

struct Value: Decodable {
    let name: String?
}