如何解析不同结构的请求 swift

How to parse a requests for different structures swift

我有几个 URL,因此,每个 URL 都有一个数据结构。 网址:

case "Get Day":
     return "time/get_day.php"
case "Get Time":
     return "time/get_time.php"
case "Get Current Time":
     return "user/get_current_time.php"

结构:

struct Day: Codable {
    var status: Int? = nil
    var error_message: String? = nil
    var result: [Result]? = nil

}

struct Time: Codable {
    let status: Int?
    let error_message: String?
    let result: [Result]?
    
    struct Result: Codable {
        let id: String
        let startTime: String
        let endTime: String
    }
}

struct CurrentTime: Codable {
    let status: Int?
    let error_message: String?
    let current_time: Int?
}

struct Result: Codable {
    let id: String
    let name_en: String
    let name_ru: String
    let name_kk: String
}

目前我有一个parseJson()函数。我可以在其中手动更改结构类型以逐一解析。但是我想不出如何做到这一点,这样我就不会手动更改代码中的任何内容。

func parseJson(data: Data)  {
        let decoder = JSONDecoder()

        do {
            let parsedData = try decoder.decode(Day.self, from: data)
            
            print(parsedData)
        } catch {
            print("Error parsing Json:\(error)")
        }
    }

如果您有示例或想法,请与我分享。

// Generic function to decode any decodable struct
func parseJson<T: Decodable>(data: Data) -> T?  {
    let decoder = JSONDecoder()
    do {
        let parsedData = try decoder.decode(T.self, from: data)
        return parsedData
    } catch {
        return nil
    }
}

// Usage
let someDay: Day? = parseJson(data: dayData)
let sometime: Time? = parseJson(data: timeData)