Encode struct and convert to dictionary [String : Any]

为君一笑 提交于 2019-12-24 20:19:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!