问题
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
}
]
回答1:
This is correct:
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: [])
You've got two problems:
var selectedAwards = [DetailViewModel]()
- wrong
selectedAwards
is an Array. Not a dictionary
来源:https://stackoverflow.com/questions/47922485/encode-struct-and-convert-to-dictionary-string-any