【问题标题】:How to map array using ObjectMapper?如何使用 ObjectMapper 映射数组?
【发布时间】:2020-02-28 20:15:11
【问题描述】:

这是我的模型

class ResponseDataType: Mappable {

    var status: Int?
    var message: String?
    var info: [Info]?

    required init?(map: Map) { }

    func mapping(map: Map) {
        status <- map["status"]
        message <- map["message"]
        info <- map["member_info"]
    }
}

这是我的 JSON

"status": 200,
    "data": {
        "member_info": [
            {
                "fullname": "werwerwer",
                "type": "werwer",
                "profile_image": "sdfsdfsd.jpg",
                "email": "wfwe@werwegt",
                "contact": ""
            }
        ]
    },
    "message": "Login Success"
}

我很难将数组映射到数据中。请告诉我我的代码有什么问题。

【问题讨论】:

  • 是否有充分的理由不使用 Codable?

标签: ios swift objectmapper


【解决方案1】:

您忘记了数据。应该是这样的:

class ResponseDataType: Mappable {

var status: Int?
var message: String?
var data: Data?

required init?(map: Map) { }

func mapping(map: Map) {
    status <- map["status"]
    message <- map["message"]
    data <- map["data"]
}

和你的数据类:

class Data: Mappable {

var info: [Info]?

required init?(map: Map) { }

func mapping(map: Map) {
    info <- map["member_info"]
}

【讨论】:

    【解决方案2】:

    如果您的 Info 对象符合 Mappable,则一切都应该在您的代码中正常工作。但是尝试阅读 Codable 协议,用它来映射对象要容易得多!

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2015-10-25
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      相关资源
      最近更新 更多