我有点担心如何使用Alamofire发布这个json数组。我看过How can I use Swift’s Codable to encode into a dictionary?和其他一些人,但我似乎无法让它工作。
我在UITableView中添加几行,在编码之前看起来像这样。
[proj.DetailViewModel(Quantity: 1, RedeemedLocationID: 6, Points: 10),
proj.DetailViewModel(Quantity: 2, RedeemedLocationID: 6, Points: 12)]
struct DetailViewModel: Codable {
var Quantity: Int!
var RedeemedLocationID: Int!
var Points: Int!
}
var selectedAwards = [DetailViewModel]()
let jsonData = try JSONEncoder().encode(selectedAwards)
// error nil
let dict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
// error nil
let struct1 = selectedAwards
let dict = try struct1.asDictionary()
如果我使用SwiftyJson来检查它看起来像这样
let json = JSON(jsonData)
print(json)
[
{
"Points" : 10,
"Quantity" : 1,
"RedeemedLocationID" : 6
},
{
"Points" : 12,
"Quantity" : 2,
"RedeemedLocationID" : 6
}
]
这是对的:
struct DetailViewModel: Codable {
var Quantity: Int
var RedeemedLocationID: Int
var Points: Int
}
var selectedAwards = [DetailViewModel(Quantity: 1, RedeemedLocationID: 6, Points: 10),
DetailViewModel(Quantity: 2, RedeemedLocationID: 6, Points: 12)]
let jsonData = try JSONEncoder().encode(selectedAwards)
let array = try JSONSerialization.jsonObject(with: jsonData, options: [])
你有两个问题:
var selectedAwards = [DetailViewModel]()
- 错了
selectedAwards
是一个数组。不是字典