[英]Decoding Complex Nested JSON in Swift 4 Lots of Errors
我正在嘗試將 model 這個嵌套的 JSON 轉換為可讀的 object 在 ZAE832E9B5BDA2699DB45F 中遇到很多不必要的 556 問題。 我想將聖經從 JSON 加載到我的應用程序中,這樣我就可以從數據角度使用它。 這是我的代碼:
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
}
這是 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."
},
(原諒可讀性)
首先,我擁有的 model 不會讓我訪問我想要的數據。 目前 Swift 沒有讀取我在結構中的一個字段,即使它就在那里。 它給了我所有類型的錯誤,所以我注釋掉了聖經結構中的章節字段。 我取消注釋它,現在 Swift 就像它不存在一樣,現在我也無法訪問它。
我做錯了什么?
代替
var verses: [Verse]
和
var verses: [[String:String]]
嘗試這個:
import Foundation
// MARK: - Bible
struct Bible: Codable {
let book: String
let chapters: [Chapter]
}
// MARK: - Chapter
struct Chapter: Codable {
let chapter: String
let verses: [[String: String]]
}
為了解碼 JSON 我使用了這個:
func fetchBible() {
let urlString = "https://raw.githubusercontent.com/aruljohn/Bible-kjv/master/Genesis.json"
guard let url = URL(string: urlString) else {
print("Not url")
return
}
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error!.localizedDescription)
return
}
guard let bible = try? JSONDecoder().decode(Bible.self, from: data) else {
print("Error decoding JSON")
return
}
DispatchQueue.main.async {
print(bible)
}
}
task.resume()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.