I am trying to model this nested JSON here into a readable object in Swift, but I am running into lots of unnecessary issues. I want to load the Bible into my app from JSON so I can play with it from a data perspective. Here is my code:
struct Bible: Codable {
var book: String
var chapters: [Chapter]
}
struct Chapter: Codable {
var chapter: String
var verses: [Verse]
}
struct Verse: Codable {
var verse: [String:String]
}
import UIKit
class ViewController: UIViewController {
var bible: Bible?
var myText: String?
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://raw.githubusercontent.com/aruljohn/Bible-kjv/master/Genesis.json"
if let url = URL(string: urlString){
if let data = try? Data(contentsOf: url){
parse(json: data)
}
}
}//end of viewDidLoad
func parse(json: Data) {
let decoder = JSONDecoder()
if let jsonBible = try? decoder.decode(Bible.self, from: json) {
bible = jsonBible.self
bible?.book = jsonBible.book
}
myText = bible!.book
print(myText)
}//end of parse
}
Here is a small sample of the JSON:
{
"book":"Genesis",
"chapters":[
{
"chapter":"1",
"verses":[
{
"1":"In the beginning God created the heaven and the earth."
},
{
"2":"And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters."
},
{
"3":"And God said, Let there be light: and there was light."
},
{
"4":"And God saw the light, that it was good: and God divided the light from the darkness."
},
{
"5":"And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day."
},
{
"6":"And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters."
},
{
"7":"And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so."
},
(Excuse the readability)
First of all the model I have will not let me access the data I want to. And currently now Swift isn't reading one of my fields in the struct even though it's right there. It was giving me all types of errors so I commented out the chapters field in the Bible struct. I uncomment it and now Swift acts like it's not there, and now I can't access that either.
What did I do wrong?
try? something: DON'T. Instead, write:` do { ... try something ... } catch { print("Error: (error)") }`. Error usually gives interesting informations about what failed, tips to fix. Read them.