【问题标题】:Swift: Convert JSON String to Array of Custom Object with ObjectMapperSwift:使用 ObjectMapper 将 JSON 字符串转换为自定义对象数组
【发布时间】:2015-03-24 16:31:11
【问题描述】:

我目前正在使用 ObjectMapper for Swift(请参阅:https://github.com/Hearst-DD/ObjectMapper/)将 String 从 HTTP 请求转换为自定义类的对象。我从请求中得到的 JSON 是一个 JSON 数组,我想将其转换为 CustomObject 类型的 Array

我试过这样:

var object = Mapper<Array<CustomObject>>().map(string: json)

然后我得到一个错误:Can not find member 'map'

这应该怎么做?

编辑:这是我的CustomObject 班级,从现在开始称为ProductVariant

public class ProductVariant: Mappable {

    /* Attributes */

    public var id = 0
//    var size : Size = nil
    public var SKU = ""
    public var stock = 0
    public var numberOfDefects = 0

    /* Constructors */

    public init?() {
        // Empty Constructor
    }

    required public init?(_ map: Map) {
        mapping(map)
    }

    /* Methods */

    public func mapping(map: Map) {
        id <- map["id"]
        SKU <- map["SKU"]
        stock <- map["stock"]
        numberOfDefects <- map["numberOfDefects"]
    }
}

【问题讨论】:

  • 我猜你没有实现 ObjectMapper 文档中给出的“Mappable 协议。如果不是这种情况,你能发布你的CustomObject 映射吗?
  • 感谢您的评论!我已经实现了Mappable 协议,并且我已经更新了我的问题。
  • 如果你使用 ObjectMapper 来映射 HTTP 响应,你应该考虑使用AlamofireObjectMapper。它是 Alamofire 的一个简单扩展,它使用 ObjectMapper 自动将您的响应转换为 swift 对象。全面披露:我是 ObjectMapper 和 AlamofireObjectMapper 的作者

标签: json swift


【解决方案1】:

我找到了一个似乎有效的解决方案:

var list: Array<ProductVariant> = Mapper<ProductVariant>().mapArray(string: json)

当我遍历数组时,它为我提供了 CustomObject 的正确属性。

我的错误是我试图将Array 放入Mapper 的类型中,如我的问题所示。

【讨论】:

  • 谢谢,我正在找这个。我可以知道你找到的来源吗?我在他们的 github 页面上找不到。
  • @Megamind 我只是通过试错才发现的,不记得我在网上的任何地方都找到了它
  • 请注意,Mapper 有多个 mapArray 函数。你想打mapArray(JSONString: String) 一个而不是 mapArray(JSON: AnyObject?) 一个。
【解决方案2】:

另一种选择是

let products = Mapper<ProductVariant>().mapArray(JSONString: json)

【讨论】:

    【解决方案3】:

    我认为您需要安装对象映射器 pod 并在文件中导入 ObjectMapper

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2013-08-29
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多