I am loading in a local json file in Swift and have used the website https://quicktype.io/ to help me build the structure quickly.
The default they give you is the contents of the response/welcome struct has optionals; and you can switch this off.
ie:
// JSON:
{
"numbers": [ 1, 2, 3 ],
"orders": [] // this is deliberate the orders can be empty at default; but can be added to in the app; for context, they will be Ints.
}
quicktype gives me:
// I've renamed Welcome in my app to Response
struct Welcome: Codable {
var numbers: [Int]?
var orders: [JSONAny]?
}
I then can use Swift JSONDecode to decode my object.
ie:
// get data from bundle (not shown)
let data = try Data(contentsOf: url)
XCTAssertTrue(data.count > 0)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .deferredToDate
decoder.keyDecodingStrategy = .convertFromSnakeCase
let response = try decoder.decode(Response.self, from: data)
Yes, I am aware because this is local data I can just make everything non-optional by default because I know the contents; but I ever save the data to disk -- I have no way of knowing if the data got corrupted/mutated, etc.
In my code, I'm treating the input as optional; as per the structure given.
However, this now means I have to unwrap/unguard the variables anytime I need to use them; which makes using filter, map, reduce, etc harder to do.
I'm thinking of just making them all mandatory just to get around this issue.
I wish to know what the best practice is for handling JSON for internal models?
Is it to have the models have their properties optional by default?
And if so; how would you check that the contents of response
are there if indeed the input is like an empty array or nil?
With thanks
If you have control over the input JSON, it makes sense not to use them as optionals, since, as you said, you don't need to unwrap the models every time you use them.
And if so; how would you check that the contents of response are there if indeed the input is like an empty array or nil?
If you try to decode a non-compliant model, an error will be thrown.