无法快速解码数据

Posted

技术标签:

【中文标题】无法快速解码数据【英文标题】:Unable to decode data Swift 【发布时间】:2019-08-01 15:52:10 【问题描述】:

我在 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: "没有关联的值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)          
    

【问题讨论】:

与错误无关,您应该删除getAllData() 中的第一个if 块。以下if/else 是多余的。 使type_id 可选。 你知道可以生成整个Codable吗?甚至是下划线标识符的翻译? @Sulthan 怎么样??? CodingKeys 没什么意义,因为您不需要查看或使用 JSON。 【参考方案1】:

您在解码过程中有明显的错误。例如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 解码器/编码器上使用密钥解码策略,例如

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

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

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

【讨论】:

没有理由担心使用下划线,因为任何人都看不到 JSON。编码/解码仅用于将数据放入 UserDefaults 中。 在哪里包含这个 let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase @King 在您创建解码器和编码器的地方,在您的getAllDatasave 方法中。

以上是关于无法快速解码数据的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 JSONDecoder 返回或解码数据

如何快速解码来自 Firebase Firestore 的时间戳

GWT 中的快速 base64 解码

无法解码交易数据

为啥无法解码这个以太坊 tx 输入数据?

什么是解码像 FAST 这样的数据协议的快速方法,其中数据以字节编码,位作为存在标志?