Visual_Novel_iOS/crush/Crush/Src/Utils/CodableHelper.swift

57 lines
1.6 KiB
Swift
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CodableHelper.swift
// Crush
//
// Created by Leon on 2025/7/13.
//
import Foundation
enum CodableHelper {
static func decode<T: Decodable>(_ type: T.Type, from data: Data) -> T? {
//try? JSONDecoder().decode(T.self, from: data)
do {
return try JSONDecoder().decode(T.self, from: data)
} catch {
dlog("❌ 解码失败: \(error)")
return nil
}
}
static func decode<T: Decodable>(_ type: T.Type, from jsonString: String) -> T? {
guard jsonString.count > 0 else{
// dlog("jsonString is empty")
return nil
}
guard let data = jsonString.data(using: .utf8) else { return nil }
return decode(type, from: data)
}
static func decode<T: Decodable>(_ type: T.Type, from dictionary: [String: Any]) -> T? {
guard let data = try? JSONSerialization.data(withJSONObject: dictionary) else { return nil }
return decode(type, from: data)
}
static func encode<T: Encodable>(_ model: T) -> Data? {
try? JSONEncoder().encode(model)
}
static func encodeToJSONString<T: Encodable>(_ model: T) -> String? {
guard let data = encode(model) else { return nil }
return String(data: data, encoding: .utf8)
}
static func printJSON<T: Encodable>(_ model: T) {
if let json = encodeToJSONString(model) {
print(json)
} else {
print("⚠️ Encode to JSON failed")
}
}
static func jsonString(from data: Data) -> String? {
String(data: data, encoding: .utf8)
}
}