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

我使用库 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
}

如果它可以帮助某人。

https://stackoverflow.com/questions/32353026/

相关文章:

json - 简单、安全的 API 认证系统

asp.net-mvc - 如何从 MVC Controller 返回 Json 对象以查看

java - 可以将 Jackson 配置为从所有字符串属性中修剪前导/尾随空格吗?

javascript - js 中奇怪的 JSON 解析行为, "Unexpected token

javascript - 如何转换为 D3 的 JSON 格式?

json - Jackson JSON Marshall 忽略 getter

python - Django: "TypeError: [] is not JSON serial

jquery - AJAX 将 JavaScript 字符串数组发布到 JsonResult 作为

php - 使用 json_encode() 时删除数组索引引用

json - 应该如何为 RESTful JSON 集合实现 HATEOAS 样式的链接?