How to create objects from SwiftyJSON

后端 未结 4 1155
面向向阳花
面向向阳花 2021-02-19 06:23

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 ?

<         


        
4条回答
  •  别那么骄傲
    2021-02-19 06:49

    You can use SwiftyJSONModel which was specifically designed for this purpose. So in your case the model would be like this:

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

    And then do like this:

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

    The framework gives you several nice features:

    1. All the keys are stored in separated enum PropertyKey
    2. No boilerplate as stringValue, intValue etc.
    3. If JSON will be invalid, framework will give a verbose error and you will immediately see what exactly went wrong

提交回复
热议问题