I wanted to parse local JSON and access inside content using JSON decoder. I'm new to JSON decoder can anyone pls suggest.
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"
}
]
}
}
]
Created Model as below:
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)
}
}
I was trying to parse and access data using this function it wasn't returning full data on the model, can anyone suggest the correct way of doing this.
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
}
Can anyone suggest correct way of doing parsing json with JSON Decoder.
decoder.decode([PremiumTutorialModel].self..., you shouldn't need any custominit(from:)for your own local json, change the json file instead and only make your properties optional if needed. Furthermore, while developing and testing you should use proper error handling when decoding. The error message are often very helpful.