使用对象映射器将本地JSON文件映射到Realm对象

时间:2019-10-16 02:40:59

标签: json swift realm objectmapper

我有本地JSON文件,我正在尝试使用ObjectMapper_Realm库将该json映射到领域对象。

var totalLessonArray = [Lesson]()
if let path = Bundle.main.path(forResource: "data", ofType: "json") {

            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let jsonResult = try JSONSerialization.jsonObject(with: data, options: [])
                totalLessonArray = Mapper<Lesson>().mapArray(JSONArray: jsonResult as! [[String : Any]])

            } catch {
                 // handle error
            }
        }

当我打印totalLessonArray时,我在4级深度列表中遇到以下错误

//...
quizScore = 0;
            quizQuestions = List<Question> <0x6000022e4d80> (
                [0] Question {
                    question = What are the synonym of sympathy? Drag and drop in the box below.;
                    answer = <Maximum depth exceeded>;
                }
            );
//...

这是模型文件

class Lesson : Object, Mappable{
    @objc dynamic var lessonNumber : Int = 0
    @objc dynamic var totalChapter : Int = 0
    @objc dynamic var completedChapter : Int = 0
    @objc dynamic var quizTaken : Bool = false
    @objc dynamic var isFinished : Bool = false
    @objc dynamic var isCurrentlyWatchingLesson : Bool = false
    @objc dynamic var currentlyWatchingChapter : Int = 0
    @objc dynamic var lessonTitle : String = ""
    @objc dynamic var quizScore : Int = 0

    var chapter = List<Chapter>()
    var quizQuestions = List<Question>()

    required convenience init?(map: Map) {
      self.init()
    }

    func mapping(map: Map) {

        lessonNumber <- map["lessonNumber"]
        totalChapter <- map["totalChapter"]
        completedChapter <- map["completedChapter"]
        quizTaken <- map["quizTaken"]
        isFinished <- map["isFinished"]
        isCurrentlyWatchingLesson <- map["isCurrentlyWatchingLesson"]
        currentlyWatchingChapter <- map["currentlyWatchingChapter"]
        lessonTitle <- map["lessonTitle"]
        quizScore <- map["quizScore"]
        chapter <- (map["chapter"], ListTransform<Chapter>())
        quizQuestions <- (map["quizQuestions"], ListTransform<Question>())
    }

}

我有4-5级深的json。我做错什么了吗?

0 个答案:

没有答案