我有一个带有变量键的字典,因此我无法映射它。我的JSON看起来像:
{
"2396": [{
"id": 21313,
"sId": 43847
}, {
"id": 21314,
"sId": 43841
}],
"2397": [{
"id": 43237,
"sId": 37321
}, {
"id": 43231,
"sId": 37342
}]
}
有什么建议吗?我已经尝试过ObjectMapper,AlamofireToJson等。
Alamofire给了我这个,但与上面的相比,它似乎不像字典:
{
2396 = ( {
id = "21313";
sid = "43847";
},
{
id = "21314";
sid = "43841";
}
);
2397 = ( {
id = "43237";
sid = "37321";
},
{
id = "43231";
sid = "37342";
}
);
}
通过以下电话:
Alamofire.request(url, method: .get, parameters: params, headers: headers())
.responseJSON{response in
print(response.result.value)
}
我想将上面的JSON映射到字典中,但可以弄清楚如何。
答案 0 :(得分:2)
创建两个对象类,一个NSObject
和另一个Mappable
:
class ID: NSObject {
var id:String!
var ids:[IDs]!
init(id:String, ids:[IDs]) {
self.id = id
self.ids = ids
}
}
class IDs: Mappable {
var id: NSInteger!
var sId: NSInteger!
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
sId <- map["sId"]
}
}
示例视图控制器类:
class ViewController: UIViewController {
var dict = [
"2396" : [
[
"id": 21313,
"sId": 43847
], [
"id" : 21314,
"sId" : 43841
]
],
"2397" : [
[
"id": 43237,
"sId": 37321
], [
"id": 43231,
"sId": 37342
]
]
]
var arrID:[ID]! = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createObject()
}
func createObject(){
for (key,value) in dict {
let ids = Mapper<IDs>().mapArray(value)!
arrID.append(ID.init(id: key, ids: ids))
}
print(arrID)
}
}
<强>输出:强>
(lldb) po arrID[0].id
"2397"
(lldb) po arrID[0].ids[0].id
43237
(lldb) po arrID[0].ids[0].sId
37321