如何从 SwiftyJSON 创建对象 [英] How to create objects from SwiftyJSON

查看:31
本文介绍了如何从 SwiftyJSON 创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a code, that parses JSON's list of questions and I can get every property. How can I iterate through the whole file and for each question create an object ?

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

    }
  }
}

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

my model of Question which objects I want to create below

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
    }

}

推荐答案

这就是我处理问题的方式.

This is how I would approach the problem.

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

Since your init inside Question does receive non optional objects, I had the feeling that the properties of Questions should be non optional too. I also converted the properties from var to let (tell me if I am wrong).

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

This is the refactored Question class. As you can see I added a class method build that receive a JSON (a SwiftyJSON) and returns a Question (if the json contains correct data), nil otherwise.

现在我不能用 failable initializer 做到这一点.

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
        }
    }
}

步骤 3

现在让我们看看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).

At line #a I put inside rootJSON the whole data received from the connection (converted into JSON).

#b 行会发生什么?

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

Well I try to access the array located inside "pack1".

rootJSON["pack1"].array?

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

If the array exists I run the map method. This will extract each cell of the array and I will be able to refer to it with the $0 parameter name inside the closure.

在闭包内部,我使用这个 json 块(应该代表一个问题)来构建一个 Question 实例.

Inside the closure I use this json block (that should represent a question) to build a Question instance.

结果将是一个 Question? 数组.如果某些子数据无效,则可能存在错误值.如果您愿意,我可以向您展示如何从此数组中删除 nil

The result will be an array of Question?. There could be ill values if some son data was not valid. If you want I can show you how to remove the nil values from this array

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

I could not try the code with real data, hope this helps.

这篇关于如何从 SwiftyJSON 创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆