gpt4 book ai didi

json - 使用 Codable 解析嵌套的 JSON

转载 作者:搜寻专家 更新时间:2023-11-01 06:56:08 32 4
gpt4 key购买 nike

所以我正在尝试使用 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 响应并将其转储到 this site 中.

它会在没有 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 并将 keyDecodingStrategy 指定为 .convertFromSnakeCase。如果您只是从 snake case 转换而来,则无需使用编码键。只有在重命名 key 时才需要它们。

如果您在其他情况下需要为响应创建自定义编码键或更改键名,this page应该会有所帮助。

你可以把它扔到 Playground 上玩:

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)

关于json - 使用 Codable 解析嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235000/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com