BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

SOLVED: Help Needed: JSON Encoding

Forums > Swift

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

   

Hi Taz You have the output to print readable however the JSON file it is probably storing like this or similar.

[{"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"}]

However if the JSONDecoder will change it to match your structs. The position that they are printed will not matter.

   

Hi Nigel,

I have never seen the encoder change the order from whats in the struct. What i worry about is being able to decode it back. I'll have to play with it tomorrow and see if I can decode it, I ran out of time today. My main concern was the encoder changing the order. Is that something the encoder would do?

I did pretty printed only for readability in this forum instead of giving one long line. Anyway, tomorrow I'll try decoding it back to see if thats an issue.

Thanks, Taz

   

My main concern was the encoder changing the order. Is that something the encoder would do?

Yep. The order doesn't matter for encoding/decoding. As long as all the fields that need to be there are there, don't worry about what order they are in.

   

Thanks @roosterboy and @NigelGee. I appreciate the clarification.

Taz

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.