【发布时间】:2018-11-18 06:42:28
【问题描述】:
我正在尝试使用 Swift 中的新(ish)可编码功能从 JSON 文件中传递一些数据。我之前使用过以下语法没有问题。但是,我相信我的设置可能有问题,因为我似乎无法理解为什么当 JSON 格式已被 JSON 解析器批准时,我一直收到以下消息。
错误信息:
error:dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.",底子错误: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON 文本没有以数组开头或允许未设置片段的对象和选项。" UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并允许未设置片段的选项。})))
我的 QuestionFactory 文件中的代码...
class QuestionFactory {
func parseJSON(filename fileName: String) -> Quiz? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
print(url)
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
print("data received is \(data.count) bytes:\n\(data)")
print(data)
print(data as NSData)
let jsonData = try decoder.decode(Quiz.self, from: data)
print(jsonData)
} catch {
print("error:\(error)")
}
}
return nil
}
}
我最初的 ViewController 中的代码:
class LaunchScreen: UIViewController {
private var quiz: Quiz?
private let jsonFileName = "QuizData"
func viewDidLoad() {
super.viewDidLoad()
createQuiz()
}
private func createQuiz() {
let questionFactory = QuestionFactory()
guard let parsedQuiz = questionFactory.parseJSON(filename: jsonFileName) else {
print("Error creating quiz")
return
}
quiz = parsedQuiz
}
func movesToMainMenuScreen() {
let transition = CATransition()
transition.duration = 1.5
transition.type = kCATransitionFade
self.navigationController?.view.layer.add(transition, forKey:nil)
let mainMenuVC: UIViewController = MainMenuViewController(quiz: quiz!) >> I am receiving an error here as well, perhaps due to my mainMenuVC's required init?
navigationController?.pushViewController(mainMenuVC, animated: false)
}
在我的 mainMenuViewController 中:
class mainMenuViewController: UIViewController {
private var quiz: Quiz! {
didSet {
tableViewAdapter = AnswerTableViewAdapter(answers: quiz.questions[0].answers) >> Although, it is not obviously reaching this far to read through the JSON.
}
required init(quiz: Quiz) {
super.init(nibName: nil, bundle: nil)
defer {
self.quiz = quiz
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
JSON 看起来像这样...
{
"questions":[
{
"text": "1. Where will the 2022 World cup be held?",
"answers": [
{
"text": "Qatar",
"isCorrect": true,
"answerType": "2"
},
{
"text": "دولة قطر",
"isCorrect": true,
"answerType": "1"
},
{
"text": "Jamaica",
"isCorrect": false,
"answerType": "0"
},
{
"image":"qatarFlag",
"isCorrect": true,
"answerType": "3"
}
]
}]
}
模型文件....
测验.swift
import Foundation
struct Quiz: Decodable {
var questions: [Question]
}
问题.swift
import Foundation
struct Question: Decodable {
var text: String
var answers: [Answer]
}
Answer.swift
import Foundation
struct Answer: Decodable {
var text: String
var image: String
var isCorrect: Bool
var answerType: String
}
【问题讨论】:
-
我认为我们需要在收到错误时查看您正在解码的 JSON 字符串以及
Quiz的定义 -
抱歉,我在完成我的问题之前点击了提交。
-
查看 (NS) 数据转储。它必须以
<7b开头 -
我将您当前的 JSON 复制粘贴到 JSON 验证器中,但它似乎无效。最后你有额外的
}]。还是您的示例中有错字? -
" /* \n 开头。您的文件中有一个标题/注释,并且 JSON 中没有注释(参见 stackoverflow.com/a/4183018/1801544)。删除它。
标签: json swift jsondecoder