iOS - 在 swift 中使用 ObjectMapper 映射根 JSON 数组

标签 ios json swift nsarray

我使用库 ObjectMapper 将 json 与我的对象映射,但我在映射根 json 数组时遇到了一些问题。

这是收到的json:

[
   {
       CustomerId = "A000015",
       ...
   },
   {
       CustomerId = "A000016",
       ...
   },
   {
       CustomerId = "A000017",
       ...
   }
]

这是我的对象

class Customer : Mappable
{
    var CustomerId : String? = nil

    class func newInstance(map: Map) -> Mappable? {
        return Customer()
    }

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

我将 Controller 中的 json 映射为

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSArray

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customers = Mapper<Customer>().map(json)
}

但是不行,我试过Mapper<[Customer]>().map(json)但它也不起作用。 最后,我尝试创建一个包含 Customer 数组的新 swift 对象 CustomerList,但它不起作用。

您知道如何映射根数组的 json 吗?

谢谢。

最佳答案

我终于解决了我的问题:

Controller 中的映射方法应该是

let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error)

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customer = Mapper<Customer>().mapArray(json)! //Swift 2
    var customer = Mapper<Customer>().mapArray(JSONArray: json)! //Swift 3
}

如果它可以帮助某人。

关于iOS - 在 swift 中使用 ObjectMapper 映射根 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32353026/

相关文章:

javascript - 如何在 ASP.NET MVC 中从 JSON 呈现 FullCalendar 中的事件?

json - 响应应该具有两个给定属性中的任何一个

objective-c - 设置 Storyboard 选项卡 Controller 、更多选项卡的导航栏颜色

ios - Swift:如何等待事件然后切换 View ?

ios - 以编程方式显示应用内购买价格

javascript - 搜索小写和大写字符

ios - Swift Keychain 不加载外部生成的 key 。 SecKey 加载 key 后无错误返回 Nil 值

swift - NSDate() 或 Date() 显示错误的时间

swift - “无法推断通用参数 'T'”

android - Kivy 获取 iDevice 和 Android ID