I'm trying to intialize an array of Item
s from a json file. To this end, I followed Apple's tutorial with re: to doing it (The algorithm is in data.swift but I'll post an abridged version down as well) My issue is that the API I'm pulling data from serves up decimals in quotation marks leading me to get the error
typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "average_cost", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
What Apple's json decoder expects:
[{
"company": "Bioseed",
"item_class": "Seeds",
"name": "9909",
"stock": 0,
"average_cost": 0.00, // Doubles without quotation marks
"otc_price": 0.00,
"dealer_price": 0.00,
"ctc_price": 0.00
}]
Sample data from my API saved in items.json
:
[{
"company": "Bioseed",
"item_class": "Seeds",
"name": "9909",
"stock": 0,
"average_cost": "0.00",
"otc_price": "0.00",
"dealer_price": "0.00",
"ctc_price": "0.00"
}]
I could probably rewrite my API to serve decimals and ints without quotation marks however it's already being used by other applications so I would rather not risk breaking something.
So is there a way to tell the decoded to ignore the quotation marks?
Item struct:
struct Item : Decodable {
var company: String
var item_class: String
var name: String
var stock: Int
var average_cost: Decimal
var otc_price: Decimal
var dealer_price: Decimal
var ctc_price: Decimal
Loading function:
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
Calling it:
let items: [Item] = load("items.json")
print(items)