【问题标题】:Handling null values from JSON处理来自 JSON 的空值
【发布时间】:2019-03-18 15:39:29
【问题描述】:

我正在尝试调用一个 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 时出错。

【问题讨论】:

标签: ios json swift


【解决方案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?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多