Home > Blockchain >  Codable Classes from Swift to Json (@Published & @StateObject)
Codable Classes from Swift to Json (@Published & @StateObject)

Time:03-14

My endgame is to print this object (below) like this in the console from the data in my app which is connected with @Published & @StateObjects.

The Object I want to create to eventually send via api (api part out of scope). One Object called "household" with a few different arrays: receiving_benefits, utility_providers, person_details, incomes, assets.

{
"household": {
    "region": "PA",
    "household_size": 1,
    "receiving_benefits": [
    ],
    "energy_crisis": false,
    "utility_providers": [
        "peco"
    ],
    "residence_type": "other",
    "property_tax_past_due": false,
    "home_needs_repairs": false,
    "filed_previous_year_tax_return": false,
    "heating_system_needs_repairs": false,
    "at_risk_of_homelessness": false,
    "received_maximum_benefit": {
        "cip": false
    },
    "person_details": [
        {
            "age": 18,
            "marital_status": "single",
            "minimum_employment_over_extended_period": false,
            "work_status": "recent_loss",
            "pregnant": false,
            "attending_school": false,
            "disabled": false
        }
    ],
    "incomes": [
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "current"
        },
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "previous"
        }
    ],
    "assets": [
        {
            "amount": 1000,
            "countable_group": "household"
        }
    ]
}
}

The classes I have in a file called Eligible are the follow, but I'll only expand on the ones I believe are important:

class Incomes : ObservableObject, Codable {...}

class Assets : ObservableObject, Codable {...}

class Person_details : ObservableObject, Codable {...}

class Received_maximum_benefit : ObservableObject, Codable {...}

class Base : ObservableObject, Codable {
    @Published var household: Household?
    enum CodingKeys: String, CodingKey {
        case household = "household"
    }
    
    init() { }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(household, forKey: .household)
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        household = try container.decode(Household.self, forKey: .household)
    }
}

class Household : ObservableObject, Codable {
    @Published var region: String = ""
    @Published var household_size: Int = 1
    @Published var receiving_benefits : [String]?
    @Published var energy_crisis : Bool = false
    @Published var utility_providers: [String] = [""]
    @Published var residence_type : String = ""
    @Published var property_tax_past_due : Bool = false
    @Published var home_needs_repairs : Bool = false
    @Published var filed_previous_year_tax_return : Bool = false
    @Published var heating_system_needs_repairs : Bool = false
    @Published var at_risk_of_homelessness: Bool = false
    @Published var received_maximum_benefit : Received_maximum_benefit?
    @Published var person_details : [Person_details]?
    @Published var Income : [Incomes]?
    @Published var assets : [Assets]?

    enum CodingKeys: String, CodingKey {

        case region = "region"
        case household_size = "household_size"
        case receiving_benefits = "receiving_benefits"
        case energy_crisis = "energy_crisis"
        case utility_providers = "utility_providers"
        case residence_type = "residence_type"
        case property_tax_past_due = "property_tax_past_due"
        case home_needs_repairs = "home_needs_repairs"
        case filed_previous_year_tax_return = "filed_previous_year_tax_return"
        case heating_system_needs_repairs = "heating_system_needs_repairs"
        case at_risk_of_homelessness = "at_risk_of_homelessness"
        case received_maximum_benefit = "received_maximum_benefit"
        case person_details = "person_details"
        case Income = "incomes"
        case assets = "assets"
    }
    
    init() { }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(region, forKey: .region)
        try container.encode(household_size, forKey: .household_size)
        try container.encode(receiving_benefits, forKey: .receiving_benefits)
        try container.encode(energy_crisis, forKey: .energy_crisis)
        try container.encode(utility_providers, forKey: .utility_providers)
        try container.encode(residence_type, forKey: .residence_type)
        try container.encode(property_tax_past_due, forKey: .property_tax_past_due)
        try container.encode(home_needs_repairs, forKey: .home_needs_repairs)
        try container.encode(filed_previous_year_tax_return, forKey: .filed_previous_year_tax_return)
        try container.encode(heating_system_needs_repairs, forKey: .heating_system_needs_repairs)
        try container.encode(at_risk_of_homelessness, forKey: .at_risk_of_homelessness)
        try container.encode(received_maximum_benefit, forKey: .received_maximum_benefit)
        try container.encode(person_details, forKey: .person_details)
        try container.encode(Income, forKey: .Income)
        try container.encode(assets, forKey: .assets)
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        region = try container.decode(String.self, forKey: .region)
        household_size = try container.decode(Int.self, forKey: .household_size)
        receiving_benefits = try container.decode([String].self, forKey: .receiving_benefits)
        energy_crisis = try container.decode(Bool.self, forKey: .energy_crisis)
        utility_providers = try container.decode([String].self, forKey: .utility_providers)
        residence_type = try container.decode(String.self, forKey: .residence_type)
        property_tax_past_due = try container.decode(Bool.self, forKey: .property_tax_past_due)
        home_needs_repairs = try container.decode(Bool.self, forKey: .home_needs_repairs)
        filed_previous_year_tax_return = try container.decode(Bool.self, forKey: .filed_previous_year_tax_return)
        heating_system_needs_repairs = try container.decode(Bool.self, forKey: .heating_system_needs_repairs)
        at_risk_of_homelessness = try container.decode(Bool.self, forKey: .at_risk_of_homelessness)
        received_maximum_benefit = try container.decode(Received_maximum_benefit.self, forKey: .received_maximum_benefit)
        person_details = try container.decode([Person_details].self, forKey: .person_details)
        Income = try container.decode([Incomes].self, forKey: .Income)
        assets = try container.decode([Assets].self, forKey: .assets)
    }
}

And the following are the @StateObjects in my content view connected to the classes:

@StateObject var eligBase = Base()
@StateObject var user = Household()
@StateObject var personDetails = Person_details()
@StateObject var Income = Incomes()
@StateObject var Asset = Assets()
@StateObject var RMB = Received_maximum_benefit()

Once I select a button inside the ContentView, I have the following that is prints the data into the console in json pretty format:

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted


        do {
            let data = try encoder.encode(user) 
            print(String(data: data, encoding: .utf8)!) 
        } catch {
            print("fail")
        }

has you can see based on the @StateObjects, when I ask it to encode 'user', which is the Household class, it doesn't print out the Income, Assets or PersonDetails arrays etc and only prints out the other @Published variables in the Household class like so:

{
  "filed_previous_year_tax_return" : true,
  "heating_system_needs_repairs" : false,
  "household_size" : 1,
  "assets" : null,
  "home_needs_repairs" : false,
  "person_details" : null,
  "utility_providers" : [
    "pgw"
  ],
  "energy_crisis" : false,
  "incomes" : null,
  "receiving_benefits" : null,
  "region" : "PA",
  "residence_type" : "rent",
  "received_maximum_benefit" : null,
  "at_risk_of_homelessness" : true,
  "property_tax_past_due" : false
}

I've tried to printing out the Base class but only prints out the following:

{
  "household" : null
}

Basically, not sure what I'm doing wrong or how I can recreate that payload at the top of this question but once I'm able to create that payload I'll be able to send with a API.

CodePudding user response:

To achieve your endgame, my advice is restructure your code such that you do not use these as separate classes:

class Incomes : ObservableObject, Codable {...}
class Assets : ObservableObject, Codable {...}
class Person_details : ObservableObject, Codable {...}
class Received_maximum_benefit : ObservableObject, Codable {...}
class Household : ObservableObject, Codable {...}
.....

Declare these as struct, not ObservableObject class. See sample code.

Similarly do not use these separate StateObject:

@StateObject var user = Household()
@StateObject var personDetails = Person_details()
@StateObject var Income = Incomes()
@StateObject var Asset = Assets()
@StateObject var RMB = Received_maximum_benefit()

You already have all you need in class Base : ObservableObject, Codable {...}.

Keep class Base as it is, together with @StateObject var eligBase = Base() and use those throughout your code. Finally use Base (eligBase) in your json encoding.

Sample code:

struct Household: Codable {
    var region: String
    var householdSize: Int
    var receivingBenefits: [String] 
    var energyCrisis: Bool
    var utilityProviders: [String]
    var residenceType: String
    var propertyTaxPastDue, homeNeedsRepairs, filedPreviousYearTaxReturn, heatingSystemNeedsRepairs: Bool
    var atRiskOfHomelessness: Bool
    var receivedMaximumBenefit: ReceivedMaximumBenefit
    var personDetails: [PersonDetail]
    var incomes: [Income]
    var assets: [Asset]

    enum CodingKeys: String, CodingKey {
        case region
        case householdSize = "household_size"
        case receivingBenefits = "receiving_benefits"
        case energyCrisis = "energy_crisis"
        case utilityProviders = "utility_providers"
        case residenceType = "residence_type"
        case propertyTaxPastDue = "property_tax_past_due"
        case homeNeedsRepairs = "home_needs_repairs"
        case filedPreviousYearTaxReturn = "filed_previous_year_tax_return"
        case heatingSystemNeedsRepairs = "heating_system_needs_repairs"
        case atRiskOfHomelessness = "at_risk_of_homelessness"
        case receivedMaximumBenefit = "received_maximum_benefit"
        case personDetails = "person_details"
        case incomes, assets
    }
}

struct Asset: Codable {
    var amount: Int
    var countableGroup: String

    enum CodingKeys: String, CodingKey {
        case amount
        case countableGroup = "countable_group"
    }
}

struct Income: Codable {
    var grossMonthlyAmount: Int
    var countableGroup, year: String

    enum CodingKeys: String, CodingKey {
        case grossMonthlyAmount = "gross_monthly_amount"
        case countableGroup = "countable_group"
        case year
    }
}

struct PersonDetail: Codable {
    var age: Int
    var maritalStatus: String
    var minimumEmploymentOverExtendedPeriod: Bool
    var workStatus: String
    var pregnant, attendingSchool, disabled: Bool

    enum CodingKeys: String, CodingKey {
        case age
        case maritalStatus = "marital_status"
        case minimumEmploymentOverExtendedPeriod = "minimum_employment_over_extended_period"
        case workStatus = "work_status"
        case pregnant
        case attendingSchool = "attending_school"
        case disabled
    }
}

struct ReceivedMaximumBenefit: Codable {
    var cip: Bool
}

EDIT

[1], now that we are using structs for Household and its constituents , the init() and encoding and decoding are all done for us. There is no need for complicated code here, unless there is some specialised processing to be done.

[2], here is some test code that shows how to read and write your Base(eligBase) model.

struct ContentView: View {
    @StateObject var eligBase = Base()
    
    let json = """
{
"household": {
    "region": "PA",
    "household_size": 1,
    "receiving_benefits": [
    ],
    "energy_crisis": false,
    "utility_providers": [
        "peco"
    ],
    "residence_type": "other",
    "property_tax_past_due": false,
    "home_needs_repairs": false,
    "filed_previous_year_tax_return": false,
    "heating_system_needs_repairs": false,
    "at_risk_of_homelessness": false,
    "received_maximum_benefit": {
        "cip": false
    },
    "person_details": [
        {
            "age": 18,
            "marital_status": "single",
            "minimum_employment_over_extended_period": false,
            "work_status": "recent_loss",
            "pregnant": false,
            "attending_school": false,
            "disabled": false
        }
    ],
    "incomes": [
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "current"
        },
        {
            "gross_monthly_amount": 700,
            "countable_group": "household",
            "year": "previous"
        }
    ],
    "assets": [
        {
            "amount": 1000,
            "countable_group": "household"
        }
    ]
}
}
"""
    
    var body: some View {
        Text("demo")
            .onAppear {
                print("---> reading Json \n")
                readJson()
                print("---> writing Json \n")
                writeJson()
            }
    }
    
    func readJson() {
        do {
            let elig = try JSONDecoder().decode(Base.self, from: json.data(using: .utf8)!)
            eligBase.household = elig.household
            print("\n----> eligBase.household: \(eligBase.household) \n")
        } catch {
            print("---> error: \(error)")
        }
    }
    
    func writeJson() {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        do {
            let data = try encoder.encode(eligBase)
            if let str = String(data: data, encoding: .utf8) {
                print("\n----> str: \(str) \n")
            }
        } catch {
            print("---> error: \(error)")
        }
    }
    
}
  • Related