如何忽略部分JSON?

问题描述 投票:0回答:1

在下一个 JSON 中,我想忽略第一部分。

JSON 示例:

{
  "game": {
     "friends": 10,
      "worlds": 50,
  },
  "results": [
  {
    "id": 1,
    "type": "Infantry",
  },
  {
    "id": 2,
    "type": "Cavalry",

  }
]

}

我的型号是:

struct Item {
  //MARK: Properties
  let id: Int
  let type: String
}

解码方法:

static var previewsFromJson: [Character] {
    let url = Bundle.main.url(forResource: "apiData", withExtension: "json")
    let data = try! Data(contentsOf: url!)

   let items = try! JSONDecoder().decode([Item].self, from: data)
   return items
   }
  

如何仅解码结果数组?

ios json swift
1个回答
0
投票

请勿在模型中包含任何您想忽略的内容。你的模型结构应该像@jnpdx在评论中提到的那样:

struct Container: Codable {
    let results: [Item]
    
    struct Item: Codable {
        let id: Int
        let type: String
    }
}

并将

[Item].self
替换为
Container.self

let items = try! JSONDecoder().decode(Container.self, from: data)

建议:请学习如何解码,从头开始。不着急。您可以在书籍、教程、文章中找到这个问题的答案......

© www.soinside.com 2019 - 2024. All rights reserved.