如何从SwiftyJSON创建对象

时间:2015-07-27 19:24:18

标签: swift swifty-json

我有一个代码,解析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
    }

}

4 个答案:

答案 0 :(得分:13)

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

第1步

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

第2步

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

  

目前我无法使用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)。

第#b行会发生什么?

我尝试访问位于"pack1"内的数组。

rootJSON["pack1"].array?

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

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

结果将是Question?的数组。如果某些儿子数据无效,可能会有不良值。如果您愿意,我可以向您展示如何从此数组中删除nil

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

答案 1 :(得分:7)

步骤1.我们将创建一个协议,其中包含一个构造函数方法和Model类

protocol JSONable {
    init?(parameter: JSON)
}

class Style: JSONable {
    let ID              :String!
    let name            :String!

    required init(parameter: JSON) {
        ID            = parameter["id"].stringValue
        name          = parameter["name"].stringValue
    }

    /*  JSON response format
    {
      "status": true,
      "message": "",
      "data": [
        {
          "id": 1,
          "name": "Style 1"
        },
        {
          "id": 2,
          "name": "Style 2"
        },
        {
          "id": 3,
          "name": "Style 3"
        }
      ]
    }
    */
}

步骤2.我们将创建JSON的扩展,它将JSON转换为模型类类型对象

extension JSON {
    func to<T>(type: T?) -> Any? {
        if let baseObj = type as? JSONable.Type {
            if self.type == .array {
                var arrObject: [Any] = []
                for obj in self.arrayValue {
                    let object = baseObj.init(parameter: obj)
                    arrObject.append(object!)
                }
                return arrObject
            } else {
                let object = baseObj.init(parameter: self)
                return object!
            }
        }
        return nil
    }
}

步骤3.将代码与Alamofire或其他代码一起使用。

Alamofire.request(.GET, url).validate().responseJSON { response in
        switch response.result {
            case .success(let value):
                let json = JSON(value)

                var styles: [Style] = []
                if let styleArr = json["data"].to(type: Style.self) {
                    styles = styleArr as! [Style]
                }
                print("styles: \(styles)")
            case .failure(let error):
                print(error)
        }
 }

我希望这会有用。

有关此内容的更多信息,请参阅此链接 https://github.com/SwiftyJSON/SwiftyJSON/issues/714

答案 2 :(得分:7)

您可以使用专为此目的而设计的SwiftyJSONModel。所以在你的情况下,模型将是这样的:

class Question: JSONObjectInitializable {
    enum PropertyKey: String {
        case level, questionText
        case answer1, answer2, answer3, answer4
        case correctAnswer, haveAnswered
    }

    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

    required init(object: JSONObject<PropertyKey>) throws {
        level = object.value(for: .level)
        questionText = object.value(for: .questionText)
        answer1 = object.value(for: .answer1)
        answer2 = object.value(for: .answer2)
        answer3 = object.value(for: .answer3)
        answer4 = object.value(for: .answer4)
        correctAnswer = object.value(for: .correctAnswer)
        haveAnswered = object.value(for: .haveAnswered) ?? false
    }   
}

然后这样做:

let rootJSON = JSON(data: data)
let questions = rootJSON.arrayValue.flatMap { try? Question(json: $0) }

该框架为您提供了几个不错的功能:

  1. 所有密钥都存储在单独的枚举PropertyKey
  2. 没有样板stringValueintValue
  3. 如果JSON无效,框架会发出详细错误,您会立即看到出现了什么问题

答案 3 :(得分:1)

pywintypes27.dll

应该有效