Home > Mobile >  How to parse a requests for different structures swift
How to parse a requests for different structures swift

Time:10-26

I have several URLs and, accordingly, there is a data structure for each of them. URLS:

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"

STRUCTS:

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
}

At the moment I have a parseJson () function. In which I can manually change the type of structure for parsing one by one. But I cannot think of how to do this so that I would not change anything in the code manually.

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)")
        }
    }

Please, if you have an example or ideas, share with me.

CodePudding user response:

// 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)
  • Related