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

问题描述 投票:0回答:1

我有点担心如何使用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
  }
]
swift alamofire swift4 codable
1个回答
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是一个数组。不是字典

© www.soinside.com 2019 - 2024. All rights reserved.