编码结构并转换为字典[String:Any]

时间:2017-12-21 10:06:28

标签: swift alamofire swift4 codable

我有点担心如何使用Alamofire发布这个json数组。我看过How can I use Swift’s Codable to encode into a dictionary?和其他一些人,但我似乎无法让它发挥作用。

我在UITableView中添加几行,然后再进行编码。

If containsBrackets
   indexOfOpeningBracket += 1 ' you dont want the parentheses itself but just the content
   Dim partBetween = example1.Substring(indexOfOpeningBracket, indexOfClosingBracket - indexOfOpeningBracket)
End If

如果我使用SwiftyJson来检查它看起来像这样

[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()

1 个答案:

答案 0 :(得分:0)

这是正确的:

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是一个数组。不是字典

相关问题