加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift ObjectMapper – 数组映射

发布时间:2020-12-14 04:32:13 所属栏目:百科 来源:网络整理
导读:我有一个 JSON响应,如: { total_count: 155,size: 75,authors: [{ name: "test1" id: 1 },{name: "test2" id: 2 }] } 我创建了我的对象模型并使用objectMapper来映射/解析这个json. import Foundationimport SwiftyJSONimport ObjectMapperclass Author: Ma
我有一个 JSON响应,如:

{
        total_count: 155,size: 75,authors: [{ name: "test1"
                    id: 1

                 },{name: "test2"
                    id: 2
                 }]
      }

我创建了我的对象模型并使用objectMapper来映射/解析这个json.

import Foundation
import SwiftyJSON
import ObjectMapper

class Author: Mappable {
    var id: Int!
    var name: String!

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        self.id <- map["id"]
        self.name <- map["name"]
    }

    static func fromJSONArray(_ json: JSON) -> [Author] {
        var authorArray: [Author] = []
        if json.count > 0 {
            for item in json["authors"]{
                print(item)
                authorArray.append(Mapper<Author>().map(JSONObject: item)!)
            }
        }
        return authorArray
    }

使用print(item)我可以看到对象但是,我无法进行附加工作.它给出了“在展开可选值时意外发现nil”错误.

解决方法

您的JSON无效.

例如,您可以使用JSONLint检查您的JSON有效性.

为了提高代码的安全性,请避免使用!

更换

authorArray.append(Mapper< Author>().map(JSONObject:item)!)

通过

if let author = (Mapper<Author>().map(JSONObject: item) {
    authorArray.append(author) 
} else {
    print("Unable to create Object from (item)")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读