【问题标题】:Decoding JSON when feed is inconsistent - Swift提要不一致时解码 JSON - Swift
【发布时间】:2019-05-27 02:01:26
【问题描述】:

当提要给我两个不同的结果时,我不知道如何使用可解码协议快速处理 JSON 提要。如果有多个“条目”,则 json 看起来像这样,并且条目值是一个对象数组

{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": [
    {
      "author": "Margaret Atwood",
      "nationality": "Canadian"
    },
    {
      "author": "Dan Brown",
      "nationality": "American"
    }
  ]
}

但是,如果只有一个条目,json 看起来像这样,其中条目只是一个字典

{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": {
    "author": "Margaret Atwood",
    "nationality": "Canadian"
  }
}

要解码第一种情况,我会使用以下结构

struct Book: Decodable {
    let feed: Feed
    let entry: [Entry]
}

// MARK: - Entry
struct Entry: Decodable {
    let author, nationality: String
}

// MARK: - Feed
struct Feed: Decodable {
    let publisher, country: String
}

然后使用类似这样的东西来解码检索到的数据

 let  object = try JSONDecoder().decode(Book.self, from: data)

当条目不是对象的数组时,我该如何处理?

【问题讨论】:

    标签: ios json swift decodable


    【解决方案1】:

    您可能会覆盖 Book 的解码器。您可以做的是尝试解开 [Entry],如果失败,只需尝试解开单个 Entry。

    例如:

    struct Book: Decodable {
       let feed: Feed
       let entry: [Entry] 
       init (from decoder :Decoder) throws {
         let container = try decoder.container(keyedBy: CodingKeys.self)
          do {
            value = try container.decode([Entry].self, forKey: .value)
          } catch {
            let newValue = try container.decode(Entry.self, forKey: .value)
            value = [newValue]
          }
       }
    }
    

    注意:这不是关于您想要做什么的全面示例,而只是您可以完成您想做的事情的一种方式

    【讨论】:

    • 您的第二个 value = 也需要一组额外的方括号来使其成为数组:value = [try container ...]
    • @RobNapier 我并没有真正尝试逐行给出代码,而是给出一般的想法(编译器会抱怨它需要抱怨的方式),但我更新了它,所以它考虑到了。跨度>
    • 我知道,但是那个特定的错误会引起足够的混乱,我希望读者会错过你的答案其余部分的价值(这很好)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2021-12-14
    • 2020-11-28
    相关资源
    最近更新 更多