I use the library ObjectMapper to map json with my objects but I have some issues to map a root json Array.

这是收到的json:

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

This is my object

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

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

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

I map the json in my controller with

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)
}

But it doesn't work, I tried Mapper<[Customer]>().map(json) but it doesn't work too. Finally I tried to create a new swift object CustomerList containing a Customer array but it doesn't work.

Do you have an idea of how to map json of a root array ?

谢谢

推荐答案

我终于解决了我的问题:

控制器中的映射方法应为

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
}

如果它能帮助别人.

Json相关问答推荐

JOLT规范:转移到现有数组

使用JQ从jsonl文件中删除具有匹配键/值的行

将PNG图像保存为Python中的JSON文件

合并2个嵌套词典

交换键和数组值,将旧键转换为新数组值,使用 jq

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

具有 (RegEx) 模式的 json-schema 中的枚举

Flutter:在本地文件 json 中搜索特殊的阿拉伯字符

向 JSON 文件添加注释

如何使用 CORS 实现 JavaScript Google Places API 请求

在 Rails 中使用 JSON 创建嵌套对象

Rails 中奇怪的 JSON Javascript 问题

对象序列化为 JSON(使用 Gson).如何在 UpperCamelCase 中设置字段名称?

直接从 Java 中的模型类创建 JSON 对象

Gson 将一组数据对象转换为 json - Android

如何向 json IAM 策略添加 comments ?

Laravel 5 控制器将 JSON 整数作为字符串发送

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

为什么 RestTemplate 不将响应表示绑定到 PagedResources?

Backbone.js 模型与集合