【发布时间】:2021-12-22 15:45:27
【问题描述】:
我想解析本地 JSON 并使用 JSON 解码器访问内部内容。我是 JSON 解码器的新手,任何人都可以建议。
JSON:
[
{
"bookmark_intro": {
"title": "What's new in bookmarks",
"enabled": "yes",
"content": [
{
"subtitle": "Organize with folders",
"content": "Organize your bookmarks in folders for quick and easy access.",
"icon": "image1.png"
},
{
"subtitle": "Share and subscribe",
"content": "Share your folders with your colleagues and subscribe to their folders to keep you informed about updates.",
"icon": "image2.png"
},
{
"subtitle": "And lots more!",
"content": "Edit bookmarks easier, add bookmarks to multiple folders - all that even offline and synced across all your apps and devices.",
"icon": "image3.png"
}
]
}
}
]
创建模型如下:
struct PremiumTutorialModel : Codable {
let bookmark_intro : Bookmark_intro?
enum CodingKeys: String, CodingKey {
case bookmark_intro = "bookmark_intro"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
bookmark_intro = try values.decodeIfPresent(Bookmark_intro.self, forKey: .bookmark_intro)
}
}
struct Bookmark_intro : Codable {
let title : String?
let enabled : String?
let content : [Content]?
enum CodingKeys: String, CodingKey {
case title = "title"
case enabled = "enabled"
case content = "content"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decodeIfPresent(String.self, forKey: .title)
enabled = try values.decodeIfPresent(String.self, forKey: .enabled)
content = try values.decodeIfPresent([Content].self, forKey: .content)
}
}
struct Content : Codable {
let subtitle : String?
let content : String?
let icon : String?
enum CodingKeys: String, CodingKey {
case subtitle = "subtitle"
case content = "content"
case icon = "icon"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
subtitle = try values.decodeIfPresent(String.self, forKey: .subtitle)
content = try values.decodeIfPresent(String.self, forKey: .content)
icon = try values.decodeIfPresent(String.self, forKey: .icon)
}
}
我试图使用这个函数解析和访问数据,它没有返回模型上的完整数据,任何人都可以提出正确的方法。
func loadJson(fileName: String) -> PremiumTutorialModel? {
let decoder = JSONDecoder()
guard
let url = Bundle.main.url(forResource: fileName, withExtension: "json"),
let data = try? Data(contentsOf: url),
let model = try? decoder.decode(PremiumTutorialModel.self, from: data)
else {
return nil
}
return model
}
谁能建议使用 JSON 解码器解析 json 的正确方法。
【问题讨论】:
-
对于初学者来说,你的 json 中最外层的类型是一个数组,所以它应该是
decoder.decode([PremiumTutorialModel].self...,你不应该为你自己的本地 json 自定义任何init(from:),改为更改 json 文件并仅在需要时使您的属性可选。此外,在开发和测试时,您应该在解码时使用适当的错误处理。错误消息通常很有帮助。
标签: swift jsondecoder