Я пытался использовать кодируемый в качестве модального класса, но я не могу обработать строку NULL, возвращенную в переменные Int - PullRequest
0 голосов
/ 10 января 2020

Мне было интересно, почему я получаю эту ошибку. API дает ответ некоторых объектов int в виде строки "". Как справиться с этим? Я пробовал свои модальные данные с использованием CODABLE и DECODABLE, но я не могу успешно извлечь данные с помощью JSONDECORDER. Почему это так?

typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "accounts", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "mask", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil))

Мой Json файл выглядит следующим образом

{
    accounts =     (
                {
            "account_id" = vzbn56oy65iwMM8kMM5jtb4Vv59dkGcWzNZP8;
            balances =             {
                available = 100;
                current = 110;
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 0000;
            name = "Plaid Checking";
            "official_name" = "Plaid Gold Standard 0% Interest Checking";
            subtype = checking;
            type = depository;
        },
                {
            "account_id" = RLJDVlp6lVfLjjMajjvJC5keAZxbVpSRlDoLD;
            balances =             {
                available = 200;
                current = 210;
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 1111;
            name = "Plaid Saving";
            "official_name" = "Plaid Silver Standard 0.1% Interest Saving";
            subtype = savings;
            type = depository;
        },
                {
            "account_id" = 6MJEmkG5kmtGEEKrEEm5ibz9mqGkjLcg9NPq4;
            balances =             {
                available = "<null>";
                current = 1000;
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 2222;
            name = "Plaid CD";
            "official_name" = "Plaid Bronze Standard 0.2% Interest CD";
            subtype = cd;
            type = depository;
        },
                {
            "account_id" = XlpW13A631fkDD1nDDzBf6AG93bLdetd6Vvr3;
            balances =             {
                available = "<null>";
                current = 410;
                "iso_currency_code" = USD;
                limit = 2000;
                "unofficial_currency_code" = "<null>";
            };
            mask = 3333;
            name = "Plaid Credit Card";
            "official_name" = "Plaid Diamond 12.5% APR Interest Credit Card";
            subtype = "credit card";
            type = credit;
        },
                {
            "account_id" = D3KDREk6ERHnzzQBzz9Nhv159AEX3bivwVLrB;
            balances =             {
                available = 43200;
                current = 43200;
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 4444;
            name = "Plaid Money Market";
            "official_name" = "Plaid Platinum Standard 1.85% Interest Money Market";
            subtype = "money market";
            type = depository;
        },
                {
            "account_id" = 8L4EwobAowfR11zn11pXHdK1pVPX5MCw1MJRj;
            balances =             {
                available = "<null>";
                current = "320.76";
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 5555;
            name = "Plaid IRA";
            "official_name" = "<null>";
            subtype = ira;
            type = investment;
        },
                {
            "account_id" = ExRDNLdbLNfK11rV11lPfygGEADjvkcXRG5Mk;
            balances =             {
                available = "<null>";
                current = "23631.9805";
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 6666;
            name = "Plaid 401k";
            "official_name" = "<null>";
            subtype = 401k;
            type = investment;
        },
                {
            "account_id" = WEwD8BWVB8fGVVwvVVgLiBwoljvXzncl9nQ5E;
            balances =             {
                available = "<null>";
                current = 65262;
                "iso_currency_code" = USD;
                limit = "<null>";
                "unofficial_currency_code" = "<null>";
            };
            mask = 7777;
            name = "Plaid Student Loan";
            "official_name" = "<null>";
            subtype = student;
            type = loan;
        }
    );
    item =     {
        "available_products" =         (
            assets,
            balance,
            "credit_details",
            identity,
            income,
            liabilities,
            transactions
        );
        "billed_products" =         (
            auth
        );
        error = "<null>";
        "institution_id" = "ins_1";
        "item_id" = rlXnR6M16Rf1RRwmRRkaFbW4BZAD4gtl1jlzw;
        webhook = "";
    };
    "request_id" = dSQFlL5uvXuVmL1;
}

Я перечисляю вниз мой МОДАЛЬНЫЙ КЛАСС.

struct Balance : Codable
{
    var available : Int
    var current : Int
    var isoCurrencyCode : String
    var limit : Int
    var unofficialCurrencyCode : String

    enum CodingKeys: String, CodingKey
    {

        case available = "available"
        case current = "current"
        case isoCurrencyCode = "iso_currency_code"
        case limit = "limit"
        case unofficialCurrencyCode = "unofficial_currency_code"
    }

    //    init(available:Int,current:Int,isoCurrencyCode:String,limit:Int,unofficialCurrencyCode:String)
    //    {
    //        self.available = available
    //        self.current = current
    //        self.isoCurrencyCode = isoCurrencyCode
    //        self.limit = limit
    //        self.unofficialCurrencyCode = unofficialCurrencyCode
    //
    //    }
    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.available = try container.decodeIfPresent(Int.self, forKey: .available) ?? 0
        self.current = try container.decodeIfPresent(Int.self, forKey: .current) ?? 0
        self.isoCurrencyCode = try container.decodeIfPresent(String.self, forKey: .isoCurrencyCode) ?? ""
        self.limit = try container.decodeIfPresent(Int.self, forKey: .limit) ?? 0
        self.unofficialCurrencyCode = try container.decodeIfPresent(String.self, forKey: .unofficialCurrencyCode) ?? ""

    }
    func encode(to encoder: Encoder) throws {

        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(available, forKey: .available)
        try container.encode(current, forKey: .current)
        try container.encode(isoCurrencyCode, forKey: .isoCurrencyCode)
        try container.encode(limit, forKey: .limit)
        try container.encode(unofficialCurrencyCode, forKey: .unofficialCurrencyCode)
    }



}

struct Accounts : Codable
{
    var accountId : String
    var balances : Balance
    var mask : Int
    var name : String
    var officialName : String
    var subtype : String
    var type : String


    init(from decoder: Decoder,balances: Balance) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.accountId = try container.decodeIfPresent(String.self, forKey: .accountId) ?? ""
        self.balances = balances
        self.mask = try container.decodeIfPresent(Int.self, forKey: .mask) ?? 0
        self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
        self.officialName = try container.decodeIfPresent(String.self, forKey: .officialName) ?? ""
        self.subtype = try container.decodeIfPresent(String.self, forKey: .subtype) ?? ""
        self.type = try container.decodeIfPresent(String.self, forKey: .type) ?? ""
    }
    func encode(to encoder: Encoder) throws {

        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(accountId, forKey: .accountId)
        try container.encode(balances, forKey: .balances)
        try container.encode(mask, forKey: .mask)
        try container.encode(name, forKey: .name)
        try container.encode(officialName, forKey: .officialName)
        try container.encode(subtype, forKey: .subtype)
        try container.encode(subtype, forKey: .subtype)
    }

    //    init(accountId:String,balances: Balance,mask:String,name:String,officialName:String,subtype:String,type:String)
    //    {
    //        self.accountId = accountId
    //        self.balances = balances
    //        self.mask = mask
    //        self.name = name
    //        self.officialName = officialName
    //        self.subtype = subtype
    //        self.type = subtype
    //
    //    }
    enum CodingKeys: String, CodingKey
    {

        case accountId = "account_id"
        case balances = "balances"
        case mask = "mask"
        case name = "name"
        case officialName = "official_name"
        case subtype = "subtype"
        case type = "type"
    }

}


struct BalanceModal : Decodable
{
    var account : [Accounts]
    var item : [ItemModal]
    var requestId : String



    init(account:[Accounts],item:[ItemModal],requestId:String)
    {
        self.account = account
        self.item = item
        self.requestId = requestId

    }

    enum CodingKeys: String, CodingKey
    {

        case account = "accounts"
        case item = "item"
        case requestId = "request_id"

    }

}

struct ItemModal : Decodable
{
    var availableProducts : [String]
    var billedProducts : [String]
    var error : String
    var institutionId : String
    var webhook : String


    //    init(availableProducts:[String], billedProducts:[String], error: String, institutionId:String, webhook:String)
    //    {
    //        self.availableProducts = availableProducts
    //        self.billedProducts = billedProducts
    //        self.error = error
    //        self.institutionId = institutionId
    //        self.webhook = webhook
    //
    //    }

    init(from decoder: Decoder,availableProducts:[String], billedProducts:[String]) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.availableProducts = availableProducts
        self.billedProducts = billedProducts
        self.error = try container.decodeIfPresent(String.self, forKey: .error) ?? ""
        self.institutionId = try container.decodeIfPresent(String.self, forKey: .institutionId) ?? ""
        self.webhook = try container.decodeIfPresent(String.self, forKey: .webhook) ?? ""

    }
    func encode(to encoder: Encoder) throws {

        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(availableProducts, forKey: .availableProducts)
        try container.encode(billedProducts, forKey: .billedProducts)
        try container.encode(error, forKey: .error)
        try container.encode(institutionId, forKey: .institutionId)
        try container.encode(webhook, forKey: .webhook)

    }

    enum CodingKeys: String, CodingKey
    {

        case availableProducts = "available_products"
        case billedProducts = "billed_products"
        case error = "error"
        case institutionId = "institution_id"
        case webhook = "webhook"


    }

}
...