簡體   English   中英

使用Codable解析嵌套的JSON

[英]Parsing nested JSON using Codable

因此,我正在嘗試在Swift中使用Codable解析看起來像這樣的JSON。

{
"abilities": [
    {
        "ability": {
            "name": "chlorophyll",
            "url": "https://pokeapi.co/api/v2/ability/34/"
        },
        "is_hidden": true,
        "slot": 3
    },
    {
        "ability": {
            "name": "overgrow",
            "url": "https://pokeapi.co/api/v2/ability/65/"
        },
        "is_hidden": false,
        "slot": 1
    }
],
"name": "SomeRandomName"
}

現在,當您嘗試獲取嵌套數據時,它會造成混亂。 現在,我正在嘗試獲取名稱,這很容易。 我也在嘗試獲得能力名稱,這對我來說很復雜。 經過研究后,我想到了這一點。

class Pokemon: Codable {

struct Ability: Codable {
    var isHidden: Bool

    struct AbilityObject: Codable {
        var name: String
        var url: String
    }

    var ability: AbilityObject

    private enum CodingKeys: String, CodingKey {
        case isHidden = "is_hidden"
        case ability
    }
}

var name: String
var abilities: [Ability]
}

現在有什么更好的方法可以執行此操作,或者我是否會堅持這樣做?

獲取您的JSON響應並將其轉儲到此站點中

它將在沒有Codable情況下生成這些結構。 添加可Codable使它們看起來像這樣:

struct Pokemon: Codable {
    let abilities: [AbilityElement]
    let name: String

    struct AbilityElement: Codable {
        let ability: Ability
        let isHidden: Bool
        let slot: Int

        struct Ability: Codable {
            let name: String
            let url: String
        }
    }
}

對於使用snake_case密鑰,您只需聲明一個JSONDecoder並將JSONDecoder指定為keyDecodingStrategy .convertFromSnakeCase 如果您只是從蛇皮箱轉換而來,則無需弄亂編碼鍵。 僅在重命名密鑰時才需要它們。

如果您在其他情況下需要創建用於響應的自定義編碼密鑰或更改密鑰名稱,則此頁面應會有所幫助。

您可以將其丟棄在操場上並玩耍:

let jsonResponse = """
{
    "abilities": [
    {
        "ability": {
        "name": "chlorophyll",
        "url": "https://pokeapi.co/api/v2/ability/34/"
    },
    "is_hidden": true,
    "slot": 3
    },
    {
    "ability": {
        "name": "overgrow",
        "url": "https://pokeapi.co/api/v2/ability/65/"
    },
    "is_hidden": false,
    "slot": 1
    }
    ],
    "name": "SomeRandomName"
}
"""

struct Pokemon: Codable {
    let abilities: [AbilityElement]
    let name: String

    struct AbilityElement: Codable {
        let ability: Ability
        let isHidden: Bool
        let slot: Int

        struct Ability: Codable {
            let name: String
            let url: String
        }
    }
}

var pokemon: Pokemon?

do {
    let jsonDecoder = JSONDecoder()
    jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
    if let data = jsonResponse.data(using: .utf8) {
        pokemon = try jsonDecoder.decode(Pokemon.self, from: data)
    }
} catch {
    print("Something went horribly wrong:", error.localizedDescription)
}

print(pokemon)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM