gpt4 book ai didi

swift - 解码 JSON 中的可选值 - Swift 4

转载 作者:行者123 更新时间:2023-11-30 10:52:32 25 4
gpt4 key购买 nike

我读过很多教程并在这里搜索答案;

Decoding Nested JSON with Optional Values Swift 4

Swift 4 Not decoding JSON optional properly

使用下面的代码解码选项似乎没有问题。显然我做错了什么,但那是什么!?

我的部分代码:

struct ProductInfo: Codable {
var name: String?
let images: [Image]
var ingredients: String?
let origin: [Origin]
let producer: Producer

enum CodingKeys: String, CodingKey {
case name = "Artikelbenamning"
case images = "Bilder"
case ingredients = "Ingrediensforteckning"
case origin = "Tillverkningslander"
case producer = "Varumarke"
}

init(from decoder: Decoder) throws {

let values = try decoder.container(keyedBy: CodingKeys.self)

name = try? values.decodeIfPresent(String.self, forKey: .name)!
images = try values.decodeIfPresent([Image].self, forKey: .images)!
ingredients = try? values.decodeIfPresent(String.self, forKey: .ingredients)!
origin = try values.decodeIfPresent([Origin].self, forKey: .origin)!
producer = try values.decodeIfPresent(Producer.self, forKey: .producer)!
}
}

应用程序查询产品数据库。当产品不存在时,返回以下json。尝试在 init(from:) 中解码 nil name(“Artikelbenamning in json)”时,应用程序崩溃。

{
"GTIN": null,
"TillverkarensArtikelnummer": null,
"Artikelbenamning": null,
"RegleratProduktnamn": null,
"Forvaringsinstruktion": null,
"Variabelmattsindikator": false,
"Bruttovikt": null,
"Bredd": null,
"Djup": null,
"Hojd": null,
"Returemballage": false,
"FarligtGodsKod": null,
"FarligtGodsKlass": null,
"FarligtGodsForpackningsgrupp": null,
"GPCKod": null,
"GiltigFROM": null,
"Publiceringsdatum": null,
"FakturerbarEnhet": false,
"Slutdatum": null,
"GiltighetsdatumPris": null,
"Tillganglighetstidpunkt": null,
"SistaTillganglighetstidpunkt": null,
"SkapadDatum": null,
"SenastAndradDatum": null,
"Flampunkt": null,
"KodBegransadMangd": null,
"OfficiellTransportbenamning": null,
"OspecificeradTransportbenamning": null,
"TunnelrestriktionADR": null,
"KlassificeringskodFarligtgods": null,
"Transportkategori": null,
"Konsumentartikel": false,
"BestallningsbarForpackning": false,
"RabattOlaglig": null,
"Garantiloptid": 0,
"Konsumentdatum": null,
"Tjanst": false,
"Sasongsindikator": null,
"Engangskop": null,
"AntalReturnerbaraEnheter": 0,
"Staplingsriktning": null,
"Staplingstyp": null,
"MaxTransportTemperatur": 0.0,
"MinTransportTemperatur": 0.0,
"Anvandningsinstruktioner": null,
"HallbarhetEfterOppning": 0,
"Riskfras": null,
"KodlistutgivareRiskfras": null,
"Klassificeringssystem": null,
"FarligtGodsBegransadMangd": null,
"FarligtGodsOvrigInfo": null,
"FarligtGodsSarbestammelser": null,
"T3495_Artikelavisering": null,
"T4032_TypAvUtgangsdatum": null,
"T3742_ForstaLeveransdatum": null,
"Undervarumarke": null,
"Niva": null,
"Produktbladslank": null,
"KompletterandeProduktklass": null,
"T4200_AllmänPubliceringstidpunkt": null,
"T3848_TypAvTryckkanslighet": null,
"Varningsetiketter": [],
"Sasongskoder": [],
"Produktklasser": [],
"MaskinellMarkningar": [],
"Bilder": [],
"ReferenserTillAndraArtiklar": [],
"MSRKritierier": [],
"Kravspecifikationer": [],
"Receptlinks": [],
"Allergener": [],
"Markningar": [],
"Ingredienser": [],
"Tillagningsinformation": [],
"Tillverkningslander": [],
"Naringsinfo": [],
"Serveringsforslag": [],
"Diettyper": [],
"Tillagningsmetoder": [],
"Farger": [],
"VillkorForsaljning": [],
"Varumarke": {
"Varumarke": null,
"AgareGLN": null,
"AgareNamn": null,
"Tillverkare": {
"Namn": null,
"EAN": null
}
},
"Nettoinnehall": [],
"Kontakter": [],
"Faroangivelser": [],
"Sakerhet": [],
"Forpackningar": [],
"Tillsatser": [],
"Substanser": [],
"Fangstzoner": [],
"Marknadsbudskap": null,
"KortMarknadsbudskap": null,
"Komponenter": null
}

最佳答案

在这种情况下,API decodeIfPresent 毫无意义,因为 key 确实存在。

具有 null 值的现有 key 和缺失 key 是两种不同的情况。

并且永远不要在 init(from Decoder 方法中强制解开包装。

有两个选项:

  1. 删除整个 init 方法,然后可选结构成员处理 null 值。
  2. 使用常规解码并忽略错误

    name = try? values.decode(String.self, forKey: .name)

关于swift - 解码 JSON 中的可选值 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311983/

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