I am trying to encode my apps data so you could share the data with someone else. That all is working fine. The issue is that the encoded data doesn't match my struct. I am writing the data out to a file.
Any help would be appreciated. I just don't know why the encoder is not putting the keys in the same order they are in the struct.
Data Struct
struct ProgramsJSON: Codable {
let id: UUID
let name: String
let date: String
let type: Int32
let emailed: Int32
let descriptors: [DescriptorJSON]
}
struct DescriptorJSON: Codable {
let id: UUID
let hymnID: UUID
let name: String
let number: String
let position: Int32
let usageType: Int32
}
Code I wrote:
var currentPrograms = [ProgramsJSON]()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try encoder.encode(currentPrograms)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let pathWithFileName = documentDirectory?.appendingPathComponent("MyLibrary", conformingTo: .json)
do {
try jsonData.write(to: pathWithFileName!)
print("Path to JSON: \(String(describing: pathWithFileName))")
} catch let error as NSError {
NSLog("Error writing JSON data to file \(error.localizedDescription)")
}
Data Output in file:
[
{
"emailed" : 0,
"id" : "750F3FA6-AF37-4DF7-8A78-699F77BF4351",
"descriptors" : [
{
"usageType" : 0,
"id" : "790CE9C2-601B-4F86-987F-8C8929116709",
"number" : "1",
"name" : "The Morning Breaks",
"position" : 0,
"hymnID" : "D40D38DC-DDE1-4755-9EAF-B80A1853918F"
},
{
"usageType" : 3,
"id" : "92251D5E-52BA-4365-9CD9-3797464FC1CE",
"number" : "2",
"name" : "The Spirit of God",
"position" : 1,
"hymnID" : "83077BB2-D997-4B17-BD04-47E7F3AF138E"
}
],
"name" : "Sacrament Meeting",
"type" : 0,
"date" : "November 20, 2022"
}
]
Thanks in advance,
Taz