编码struct并转换为字典[String:任何] [英] Encode struct and convert to dictionary [String : Any]
本文介绍了编码struct并转换为字典[String:任何]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对如何使用Alamofire发布此json数组有些困惑。我看过我如何使用Swift的Codable编码成字典吗?和其他一些,但是我似乎无法正常工作。
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.
在编码之前,我从UITableView附加了几行它。
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()
如果我使用SwiftyJson只是要检查它看起来像这样
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
}
]
推荐答案
这是正确的:
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: [])
ve有两个问题:
var selectedAwards = [DetailViewModel]()
-错误
selectedAwards
是一个数组。不是字典
selectedAwards
is an Array. Not a dictionary
这篇关于编码struct并转换为字典[String:任何]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文