I'm a bit stuck on how I can post this json array using Alamofire. I've looked at How can I use Swift’s Codable to encode into a dictionary? and a few others but I can't seem to get it work.
I'm appending a few rows from a UITableView it looks like this before encoding.
[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()
If I use SwiftyJson just to check it looks like this
let json = JSON(jsonData)
print(json)
[
{
"Points" : 10,
"Quantity" : 1,
"RedeemedLocationID" : 6
},
{
"Points" : 12,
"Quantity" : 2,
"RedeemedLocationID" : 6
}
]
This is correct:
You've got two problems:
var selectedAwards = [DetailViewModel]()
- wrongselectedAwards
is an Array. Not a dictionary