【问题标题】:Encode struct and convert to dictionary [String : Any]编码结构并转换为字典 [String : Any]
【发布时间】:2017-12-21 10:06:27
【问题描述】:

我对如何使用 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】:

    这是正确的:

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

    【讨论】:

    • 我正在从 tableview 中附加行,如下所示: selectedAwards.append(DetailViewModel(Quantity: quantity, RedeemedLocationID: 6, Points: Award.Points)) 发生在 textFieldDidEndEditing 委托上。有错吗?
    • selectedAwards 不是字典。这是一个数组
    • 这就是我卡住的地方,我不知道如何继续。所以我想问题是我如何在这种方法中从数组到字典
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多