gpt4 book ai didi

swift - 如何从 SwiftyJSON 创建对象

转载 作者:IT王子 更新时间:2023-10-29 05:25:26 24 4
gpt4 key购买 nike

我有一个代码,可以解析 JSON 的问题列表,我可以获得每个属性。如何遍历整个文件并为每个问题创建一个对象?

class ViewController: UIViewController {

var hoge: JSON?

override func viewDidLoad() {
super.viewDidLoad()

let number = arc4random_uniform(1000)
let url = NSURL(string: "http://www.wirehead.ru/try-en.json?\(number)")
var request = NSURLRequest(URL: url!)
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
if data != nil {
hoge = JSON(data: data!)
let level = hoge!["pack1"][0]["level"].intValue
let questionText = hoge!["pack1"][0]["questionText"].stringValue
let answer1 = hoge!["pack1"][0]["answer1"].stringValue
let answer2 = hoge!["pack1"][0]["answer2"].stringValue
let answer3 = hoge!["pack1"][0]["answer3"].stringValue
let answer4 = hoge!["pack1"][0]["answer4"].stringValue
let correctAnswer = hoge!["pack1"][0]["correctAnswer"].stringValue
let haveAnswered = hoge!["pack1"][0]["haveAnswered"].boolValue

}
}
}

我的问题模型我想在下面创建哪些对象

class Question {

var level : Int?
var questionText : String?
var answer1 : String?
var answer2 : String?
var answer3 : String?
var answer4 : String?
var correctAnswer : String?
var haveAnswered : Bool = false

init(level: Int, questionText:String, answer1:String, answer2:String, answer3:String, answer4:String, correctAnswer: String, haveAnswered:Bool) {
self.level = level
self.questionText = questionText
self.answer1 = answer1
self.answer2 = answer2
self.answer3 = answer3
self.answer4 = answer4
self.correctAnswer = correctAnswer
self.haveAnswered = false
}

}

最佳答案

这就是我解决问题的方式。

第一步

由于 Question 中的 init 确实收到了 non optional 对象,我觉得 Questions 的属性也应该是非可选的。我还将属性从 var 转换为 let(如果我错了请告诉我)。

第二步

这是重构的 Question 类。如您所见,我添加了一个类方法 build,它接收一个 JSON(一个 SwiftyJSON)并返回一个 Question (如果 json 包含正确的数据),否则为 nil。

Right now I cannot do this with a failable initializer.

extension String {
func toBool() -> Bool? {
switch self.lowercaseString {
case "true", "1", "yes" : return true
case "false", "0", "no" : return false
default: return nil
}
}
}

class Question {

let level: Int
let questionText: String
let answer1: String
let answer2: String
let answer3: String
let answer4: String
let correctAnswer: String
let haveAnswered: Bool

init(level: Int, questionText:String, answer1:String, answer2:String, answer3:String, answer4:String, correctAnswer: String, haveAnswered:Bool) {
self.level = level
self.questionText = questionText
self.answer1 = answer1
self.answer2 = answer2
self.answer3 = answer3
self.answer4 = answer4
self.correctAnswer = correctAnswer
self.haveAnswered = false
}

class func build(json:JSON) -> Question? {
if let
level = json["level"].string?.toInt(),
questionText = json["questionText"].string,
answer1 = json["answer1"].string,
answer2 = json["answer2"].string,
answer3 = json["answer3"].string,
answer4 = json["answer4"].string,
correctAnswer = json["correctAnswer"].string,
haveAnswered = json["haveAnswered"].string?.toBool() {
return Question(
level: level,
questionText: questionText,
answer1: answer1,
answer2: answer2,
answer3: answer3,
answer4: answer4,
correctAnswer: correctAnswer,
haveAnswered: haveAnswered)
} else {
debugPrintln("bad json \(json)")
return nil
}
}
}

第三步

现在让我们看看viewDidLoad

func viewDidLoad() {
super.viewDidLoad()

let number = arc4random_uniform(1000)

if let
url = NSURL(string: "http://www.wirehead.ru/try-en.json?\(number)"),
data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: url), returningResponse: nil, error: nil) {
// line #a
let rootJSON = JSON(data: data)
// line #b
if let questions = (rootJSON["pack1"].array?.map { return Question.build($0) }) {
// now you have an array of optional questions [Question?]...
}

}
}

在 #a 行,我将所有从连接接收到的数据放入 rootJSON 中(转换为 JSON)。

第 #b 行发生了什么?

好吧,我尝试访问位于 "pack1" 中的数组。

rootJSON["pack1"].array?

如果数组存在,我运行 map 方法。这将提取数组的每个单元格,我将能够在闭包内使用 $0 参数名称引用它。

在闭包中,我使用这个 json block (应该表示一个问题)来构建一个 Question 实例。

结果将是一组 Question?。如果某些子数据无效,则可能存在不良值。如果你愿意,我可以告诉你如何从这个数组中删除 nil

我无法使用真实数据尝试代码,希望这对您有所帮助。

关于swift - 如何从 SwiftyJSON 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com