HandyJSON 解析嵌套model报错

无敌鲨鱼炮
  • 448

这是解析:

func getBlogList() {
    let url = URL.init(string: "https://www.jianshu.com/asimov/users/slug/4212f351f6b5/public_notes")!
    AF.request(url, method: .get, parameters: nil).responseString { (response) in
        switch response.result {
        case .success(let resultString):
            self.dataArray = [BlogEntity].deserialize(from: resultString)!
            self.tableView.reloadData()
        case .failure(let error):
            SVProgressHUD.showInfo(withStatus: error.errorDescription)
        }
    }
}

这是 model:

class BlogEntity: BlogBaseModel {
    
    var object: BlogObject?
    
    class BlogObject: BlogBaseModel {
        
        var type: Int = 0
        var data: BlogModel?
        
        class BlogModel: BlogBaseModel {
            
            var id = 0
            var title = ""
            var slug = ""
            var list_image_url = ""
            var first_shared_at = ""
            var public_abbr = ""
            var paid = false
            var commentable = false
            var is_top = false
            var total_fp_amount = 0
            var public_comments_count = 0
            var total_rewards_count = 0
            var likes_count = 0
            var views_count = 0
            var user: BlogUser?
            
        }
        
    }
    
}

class BlogUser: BlogBaseModel {
    var id = 0
    var nickname = ""
    var slug = ""
    var avatar = ""
}

class BlogBaseModel: HandyJSON {
    required init() {}
}

解析的时候报错:

[BlogEntity].deserialize(from: resultString)!

强制解包的错。

我看了很久也没看出是哪里出了问题。。。

注:那个url可以直接复制到浏览器打开。

回复
阅读 1k
1 个回答

试试解析的时候这样写:

if let arr = json as? [[String:Any]] {
    let dataArray = [BlogEntity].deserialize(from: arr)!
    print(dataArray)
}

我用你的写法是可以正确解析的,如果不是你没有确定json字符串的样式,那可能就是你封装的网络请求方法有问题了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏