swift - 无法解码数据 Swift

标签 swift codable userdefaults

我在 UserDefault 中保存了一些值,我试图取回它,但我无法解码它,因为它一直返回 fatalError

func save(dataPass: FeaturedProperties) {
    var saveArraData: [FeaturedProperties] = getAllData()
    saveArraData.append(dataPass)
    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(saveArraData) {
        defaults.set(encoded, forKey: key)
        defaults.synchronize()
        print("BOUNCEE CC) saveArraData \(encoded)")
    }

}

func getAllData() -> [FeaturedProperties] {
    if defaults.value(forKey: key) == nil {
        let array = [FeaturedProperties]()
        return array
    }

    if let objects = defaults.data(forKey: key) {
        let decoder = JSONDecoder()
        do {
            let objectsDecoded = try decoder.decode([FeaturedProperties].self, from: objects)
            print("BOUNCEE CC) objects \(objectsDecoded)")
            return objectsDecoded
        } catch let error {
            fatalError(error.localizedDescription)
        }
    } else {
        let array = [FeaturedProperties]()
        return array
    }
}

我能够打印数据但无法将其解码为 FeaturedProperties 任何帮助

返回的错误是

fatal keyNotFound(FeaturedPropertiesCodingKeys(stringValue: "type_id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key FeaturedPropertiesCodingKeys(stringValue: \"type_id\", intValue: nil) (\"type_id\").", underlyingError: nil)))

这是我的精选属性

struct FeaturedProperties: Codable {
    var id: Int?
    var title: String?
    var desc: String?
    var typeId: Int?
    var subTypeId: Int?
    var addressLine1: String?
    var addressLine2: String?
    var propertyPurposeId: Int?
    var isFeatured: Int?
    var securityDeposit: Int?
    var locationId: Int?
    var currency: String?
    var price: String?
    var pricePerSqm: String?
    var leasableArea: String?
    var plotSize: String?
    var plotPlate: String?
    var floorSize: String?
    var builtUpArea: String?
    var kitchenSize: String?
    var yearBuilt: String?
    var bathRoomNo: String?
    var bedroomNo: String?
    var toiletNo: String?
    var floorTypeId: String?
    var arePetAllowed: String?
    var hasKitchen: Int?
    var dateAvailable: String?
    var status: Int?
    var availabilityStatus: Int?
    var banner: String?
    var premium: Int?
    var parkingOptions: String?
    var landmarks: String?
    var featuresAndAmenities: String?
    var createdBy: Int?
    var user: User?
    var locationDetails: LocationDetails?
    var noViews: Int?
    var noClicks: Int?
    var longitude: String?
    var latitude: String?
    var isSuspended: Int?
    var createdAt: String?

    var updatedAt: String?
    var deletedAt: String?
    var propertyImage: [SearchPropertyImage]?

    enum FeaturedPropertiesCodingKeys: String, CodingKey {
        case id
        case title
        case desc = "description"
        case typeId = "type_id"
        case subTypeId = "sub_type_id"
        case addressLine1 = "address_line1"
        case addressLine2 = "address_line2"
        case propertyPurposeId = "property_purpose_id"
        case isFeatured = "is_featured"
        case securityDeposit = "security_deposit"
        case locationId = "location_id"
        case currency
        case price
        case pricePerSqm = "price_per_sqm"
        case leasableArea = "leasable_area"
        case plotSize = "plot_size"
        case plotPlate = "plot_plate"
        case floorSize = "floor_size"
        case builtUpArea = "built_up_area"
        case kitchenSize = "kitchen_size"
        case yearBuilt = "year_built"
        case bathRoomNo = "bathroom_no"
        case bedroomNo = "bedroom_no"
        case toiletNo = "toilet_no"
        case floorTypeId = "floor_type_id"
        case arePetAllowed = "are_pet_allowed"
        case hasKitchen = "has_kitchen"
        case dateAvailable = "date_available"
        case status
        case availabilityStatus = "availability_status"
        case banner
        case premium
        case parkingOptions
        case landmarks
        case featuresAndAmenities = "features_and_amenities"
        case createdBy = "created_by"
        case locationDetails = "location_details"
        case noViews = "no_views"
        case noClicks = "no_clicks"
        case longitude
        case latitude
        case isSuspended = "is_suspended"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case deletedAt = "deleted_at"
        case propertyImage = "property_image"

    }

    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: FeaturedPropertiesCodingKeys.self)

        id = try container.decode(Int.self, forKey: .id)
        title = try container.decodeIfPresent(String.self, forKey: .title)
        desc = try container.decodeIfPresent(String.self, forKey: .desc)

        typeId = try container.decode(Int.self, forKey: .typeId)
        subTypeId = try container.decode(Int.self, forKey: .subTypeId)

        addressLine1 = try container.decodeIfPresent(String.self, forKey: .addressLine1)
        addressLine2 = try container.decodeIfPresent(String.self, forKey: .addressLine2)
        propertyPurposeId = try container.decode(Int.self, forKey: .propertyPurposeId)
        isFeatured = try container.decode(Int.self, forKey: .isFeatured)
        securityDeposit = try container.decode(Int.self, forKey: .securityDeposit)
        locationId = try container.decode(Int.self, forKey: .locationId)

        currency = try container.decodeIfPresent(String.self, forKey: .currency)
        price = try container.decodeIfPresent(String.self, forKey: .price)
        pricePerSqm = try container.decodeIfPresent(String.self, forKey: .pricePerSqm)
        leasableArea = try container.decodeIfPresent(String.self, forKey: .leasableArea)
        plotSize = try container.decodeIfPresent(String.self, forKey: .plotSize)
        plotPlate = try container.decodeIfPresent(String.self, forKey: .plotPlate)

        floorSize = try container.decodeIfPresent(String.self, forKey: .floorSize)
        builtUpArea = try container.decodeIfPresent(String.self, forKey: .builtUpArea)
        kitchenSize = try container.decodeIfPresent(String.self, forKey: .kitchenSize)
        yearBuilt = try container.decodeIfPresent(String.self, forKey: .yearBuilt)
        bathRoomNo = try container.decodeIfPresent(String.self, forKey: .bathRoomNo)
        bedroomNo = try container.decodeIfPresent(String.self, forKey: .bedroomNo)

        toiletNo = try container.decodeIfPresent(String.self, forKey: .toiletNo)
        floorTypeId = try container.decodeIfPresent(String.self, forKey: .floorTypeId)
        arePetAllowed = try container.decodeIfPresent(String.self, forKey: .arePetAllowed)
        hasKitchen = try container.decode(Int.self, forKey: .hasKitchen)
        dateAvailable = try container.decodeIfPresent(String.self, forKey: .dateAvailable)
        status = try container.decode(Int.self, forKey: .status)

        availabilityStatus = try container.decode(Int.self, forKey: .availabilityStatus)
        banner = try container.decodeIfPresent(String.self, forKey: .banner)
        premium = try container.decode(Int.self, forKey: .premium)
        parkingOptions = try container.decodeIfPresent(String.self, forKey: .parkingOptions)
        landmarks = try container.decodeIfPresent(String.self, forKey: .landmarks)
        featuresAndAmenities = try container.decodeIfPresent(String.self, forKey: .featuresAndAmenities)
        createdBy = try container.decode(Int.self, forKey: .createdBy)
        noViews = try container.decode(Int.self, forKey: .noViews)
        noClicks = try container.decode(Int.self, forKey: .noClicks)

        longitude = try container.decodeIfPresent(String.self, forKey: .longitude)
        latitude = try container.decodeIfPresent(String.self, forKey: .latitude)
        isSuspended = try container.decode(Int.self, forKey: .isSuspended)
        createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt)
        locationDetails = try container.decodeIfPresent(LocationDetails.self, forKey: .locationDetails)


        updatedAt = try container.decodeIfPresent(String.self, forKey: .updatedAt)
        deletedAt = try container.decodeIfPresent(String.self, forKey: .deletedAt)
        propertyImage = try container.decodeIfPresent([SearchPropertyImage].self, forKey: .propertyImage)          
    }
}

最佳答案

你的解码过程中有明显的错误。例如,typeId 是可选的,但您使用的是 decode 而不是 decodeIfPresent。为了防止错误,让编译器为你生成一切:

struct FeaturedProperties: Codable {
    var id: Int?
    var title: String?
    var desc: String?
    var typeId: Int?
    var subTypeId: Int?
    var addressLine1: String?
    var addressLine2: String?
    var propertyPurposeId: Int?
    var isFeatured: Int?
    var securityDeposit: Int?
    var locationId: Int?
    var currency: String?
    var price: String?
    var pricePerSqm: String?
    var leasableArea: String?
    var plotSize: String?
    var plotPlate: String?
    var floorSize: String?
    var builtUpArea: String?
    var kitchenSize: String?
    var yearBuilt: String?
    var bathRoomNo: String?
    var bedroomNo: String?
    var toiletNo: String?
    var floorTypeId: String?
    var arePetAllowed: String?
    var hasKitchen: Int?
    var dateAvailable: String?
    var status: Int?
    var availabilityStatus: Int?
    var banner: String?
    var premium: Int?
    var parkingOptions: String?
    var landmarks: String?
    var featuresAndAmenities: String?
    var createdBy: Int?
    var user: User?
    var locationDetails: LocationDetails?
    var noViews: Int?
    var noClicks: Int?
    var longitude: String?
    var latitude: String?
    var isSuspended: Int?
    var createdAt: String?

    var updatedAt: String?
    var deletedAt: String?
    var propertyImage: [SearchPropertyImage]?
}

就够了。

当然,您可以添加 CodingKeys 以进行可选覆盖,但如果您的唯一目标是将驼峰式标识符转换为下划线,则可以在 JSON 解码器/编码器上使用 key 解码策略,例如

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

如果你想使用自定义编码键,枚举必须被称为CodingKeys,例如

private enum CodingKeys: String, CodingKey {
    case typeId = "type_id"
}

关于swift - 无法解码数据 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312781/

相关文章:

ios - AVplayer 不会在锁屏或后台播放来自 url 的音频

ios - 如何在 CodingKeys 枚举(可编码协议(protocol))中使用通用值

swift - 引用类型/子类化,以及对 Swift 4 Codable 和编码器/解码器的更改

swift - 如何安全地从用户默认值中解包值?

ios - 将 Set<CustomObject> 存储到 UserDefaults

ios - 带有项目的快速 slider

swift - CLLocationCoordinate2D 到一个数组

swift - 使用自定义垂直距离水平居中 subview | swift

swift - 如何使用 codable 和 swift 递归解析 json

swift - 如何将 UIView 存储在 CoreData 或 UserDefaults 中