0

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
  }
]
Misha
  • 128
  • 1
  • 12

1 Answers1

0

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

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
  • I'm appending the rows from the tableview like so: selectedAwards.append(DetailViewModel(Quantity: quantity, RedeemedLocationID: 6, Points: award.Points)) which is happening on the textFieldDidEndEditing delegate. Is that wrong? – Misha Dec 21 '17 at 10:25
  • selectedAwards is not a Dictionary. This is an Array – Vyacheslav Dec 21 '17 at 10:41
  • thats where I am stuck, I'm not sure how to proceed. So i guess the question is how can i go from an array to dictionary in this approach – Misha Dec 21 '17 at 10:56