Swift JSON 解码错误与编码密钥用法

问题描述 投票:0回答:1

我真的很感激一些帮助。我从 Laravel API 后端返回以下 JSON

[
    {
        "id": 1,
        "name": "instructor",
        "hourly_rate": "35.01",
        "bio": "Patient and experienced driving instructor specialising in new drivers",
        "profile_image": null,
        "rating": 4.8,
        "total_reviews": 25,
        "location": {
            "latitude": 51.5074,
            "longitude": -0.1278
        },
        "qualifications": [
            "ADI Certificate",
            "Grade A Instructor"
        ],
        "years_experience": 5,
        "gender": "female",
        "transmission": "Manual",
        "vehicle_type": null,
        "lesson_types": [
            "standard",
            "intensive",
            "pass_plus"
        ],
        "is_available": true
    }
]

以及以下型号

struct Instructor: Identifiable, Codable {
    let id: Int
    let name: String
    let rating: Double
    let hourlyRate: Double
    let experience: Int
    let profileImage: String?
    let description: String
    let availability: [Availability]
    let gender: InstructorGender
    let lessonTypes: [LessonType]
    let transmission: TransmissionType
    let vehicleType: String?
    let qualifications: [String]
    let isAvailable: Bool
    
    struct Availability: Codable {
        let dayOfWeek: Int
        let startTime: Date
        let endTime: Date
    }
    
    enum TransmissionType: String, Codable {
        case manual = "Manual"
        case automatic = "Automatic"
    }
    
    enum LessonType: String, Codable {
        case standard = "standard"
        case intensive = "intensive"
        case passPlus = "pass_plus"
    }
    
    enum InstructorGender: String, Codable {
        case male
        case female
        
        init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            let rawValue = try container.decode(String.self).lowercased()
            switch rawValue {
            case "male": self = .male
            case "female": self = .female
            default:
                throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid gender value: \(rawValue)")
            }
        }
    }
    
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case rating
        case hourlyRate = "hourly_rate"
        case experience = "years_experience"
        case profileImage = "profile_image"
        case description = "bio"
        case availability
        case gender
        case lessonTypes = "lesson_types"
        case transmission
        case vehicleType = "vehicle_type"
        case qualifications
        case isAvailable = "is_available"
    }
}

当我使用下面的解码器时,我收到错误

编码错误: keyNotFound(CodingKeys(stringValue: "hourly_rate", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "没有与key CodingKeys(stringValue:“hourly_rate”,intValue:nil)(“hourly_rate”)。”,underlyingError:无))

private let jsonDecoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        return decoder
    }()
    

func getBookings(token: String) async throws -> [Booking] {
        guard let url = URL(string: "\(baseURL)/bookings") else {
            throw NetworkError.invalidURL
        }

        let data = try await sendAuthenticatedRequestWithData(to: url, method: .get, token: token)

        if let jsonString = String(data: data, encoding: .utf8) {
            print("📱 Raw Bookings JSON:", jsonString)
        }

        do {
            let bookings = try jsonDecoder.decode([Booking].self, from: data)
            print("📱 Successfully decoded \(bookings.count) bookings")
            return bookings
        } catch {
            print("❌ Decoding error: \(error)")
            throw error
        }
    }
swift xcode
1个回答
0
投票

您已将

hourlyRate
声明为
Double
。但根据你的 JSON,它是
String
。 所以将
let hourlyRate: Double
更改为
let hourlyRate: String

© www.soinside.com 2019 - 2024. All rights reserved.