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