创建JSON数据项的数组



我有一个很长的json数组,其中包含看起来像这样的项目:

[
  {
    "id": "sm10-1",
    "name": "Pheromosa & Buzzwole-GX",
    "imageUrl": "https://images.pokemontcg.io/sm10/1.png",
    "subtype": "TAG TEAM",
    "supertype": "Pokémon",
    "hp": "260",
    "retreatCost": [
      "Colorless",
      "Colorless"
    ],
    "convertedRetreatCost": 2,
    "number": "1",
    "artist": "Mitsuhiro Arita",
    "rarity": "Rare Holo GX",
    "series": "Sun & Moon",
    "set": "Unbroken Bonds",
    "setCode": "sm10",
    "text": [
      "When your TAG TEAM is knocked out, your opponent takes 3 Prize Cards."
    ],
    "types": [
      "Grass"
    ],
    "attacks": [
      {
        "name": "Jet Punch",
        "cost": [
          "Grass"
        ],
        "convertedEnergyCost": 1,
        "damage": "30",
        "text": "This attack does 30 damage to 1 of your opponent's Benched Pokémon. (Don't apply Weakness and Resistance for Benched Pokémon.)"
      },
      {
        "name": "Elegant Sole",
        "cost": [
          "Grass",
          "Grass",
          "Colorless"
        ],
        "convertedEnergyCost": 3,
        "damage": "190",
        "text": "During your next turn, this Pokémon's Elegant Sole attack's base damage is 60."
      },
      {
        "name": "Beast Game-GX",
        "cost": [
          "Grass"
        ],
        "convertedEnergyCost": 1,
        "damage": "50",
        "text": "If your opponent's Pokémon is Knocked Out by damage from this attack, take 1 more Prize card. If this Pokémon has at least 7 extra Energy attached to it (in addition to this attack's cost), take 3 more Prize cards instead. (You can't use more than 1 GX attack in a game.)"
      }
    ],
    "weaknesses": [
      {
        "type": "Fire",
        "value": "×2"
      }
    ],
    "imageUrlHiRes": "https://images.pokemontcg.io/sm10/1_hires.png",
    "nationalPokedexNumber": 794
  }
]

这只是数组中数百个项目。我要做的是从每个项目中获取特定值(即名称,ImageUrl,Supertype,hp,Rarity,set(,然后将它们发送到一个结构,然后将其添加到此类结构的数组中。

我目前拥有的印刷品仅打印出所有JSON数据,我无法弄清楚如何获取单个数据并为每个单独的卡创建一系列结构。

这是我当前拥有的代码:

//[TEST] READING JSON FILE LOCALLY
struct card: Decodable {
    let name: String
    let imageUrl: String
    let supertype: String
    let artist: String
    let rarity: String
    let set: String
    let types: Array<String>
}
func loadJsonInfo() {
    do{
        let data = try Data.init(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Unbroken Bonds", ofType: "json")!))
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
        print(json)
    } catch {
        print(error)
    }
}

另外,JSON文件本地存储在我的AppData中。预先感谢您的帮助!

尝试https://quicktype.io/

您将JSON放在那里。并获取所有必要的数据结构来解码JSON

Decodable类型解码A JSON ,您需要使用JSONDecoder's decode(_:from:)方法。

将您的loadJsonInfo()方法更新为

func loadJsonInfo() {
    if let file = Bundle.main.url(forResource: "Unbroken Bonds", withExtension: "json") {
        do {
            let data = try Data(contentsOf: file)
            let arr = try JSONDecoder().decode([Card].self, from: data)
            print(arr)
        } catch {
            print(error)
        }
    }
}

注意:创建类型时使用第一字母资本,即使用Card代替card

分析代码时,您拥有来自服务器的数据。我还取下了拆开的力!因此,它不会在没有文件

的情况下崩溃
func loadJsonInfo() {
    if let path = Bundle.main.path(forResource: "Unbroken Bonds", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let result = try JSONDecoder().decode(ResultElement.self, from: data)
        } catch let error {
            print(error)
        }            
    }
}

您的模型

import Foundation
// MARK: - ResultElement
struct ResultElement: Codable {
    let id, name: String?
    let imageURL: String?
    let subtype, supertype, hp: String?
    let retreatCost: [String]?
    let convertedRetreatCost: Int?
    let number, artist, rarity, series: String?
    let resultSet, setCode: String?
    let text, types: [String]?
    let attacks: [Attack]?
    let weaknesses: [Weakness]?
    let imageURLHiRes: String?
    let nationalPokedexNumber: Int?
    enum CodingKeys: String, CodingKey {
        case id, name
        case imageURL = "imageUrl"
        case subtype, supertype, hp, retreatCost, convertedRetreatCost, number, artist, rarity, series
        case resultSet = "set"
        case setCode, text, types, attacks, weaknesses
        case imageURLHiRes = "imageUrlHiRes"
        case nationalPokedexNumber
    }
}
// MARK: - Attack
struct Attack: Codable {
    let name: String?
    let cost: [String]?
    let convertedEnergyCost: Int?
    let damage, text: String?
}
// MARK: - Weakness
struct Weakness: Codable {
    let type, value: String?
}
typealias Result = [ResultElement]

最新更新