Swiftmodel数据解析及转换
enum MKError: Error {
case message(String)
}
struct MKDecoder {
丰田霸道2700public static func decode<T>(_ type: T.Type, param: [String: Any]) throws -> T? where T: Decodable {
if param.isEmpty {
return nil
特斯拉上海车展}
guard let jsonData = JsonData(with: param) else {
ssage("转换jsonData失败")
}
guard let model = try? JSONDecoder().decode(T.self, from: jsonData) else {吉利金刚2代怎么样
ssage("转换模型失败")
科鲁兹发动机怎么样}
return model
}
public static func decode<T>(_ type: T.Type, array: [[String: Any]]) -> [T]? where T: Decodable {
if let jsonData = JsonData(with: array) {
if let models = try? JSONDecoder().decode([T].self, from: jsonData) {
return models
}
} else {
print("模型转换jsonData失败")
}
return nil
}
private static func getJsonData(with param: Any) -> Data? {
if !JSONSerialization.isValidJSONObject(param) {
return nil
}
guard let data = try? JSONSerialization.data(withJSONObject: param, options: []) else {
return nil
}
return data长城汽车集团
}
}
struct MKEncoder {
public static func encoder<T>(toString model: T) throws -> String? where T: Encodable {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? de(model) else {
ssage("转换data失败")
}
guard let jsonStr = String(data: data, encoding: .utf8) else {
ssage("转换json失败")
}
return jsonStr
}
public static func encoder<T>(toDictionary model: T) throws -> [String: Any]? where T: Encodable {豪车车祸车门被锁死
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? de(model) else {
ssage("转换data失败")
}
guard let diction = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as?
[String: Any] else {
ssage("转换dictionary失败")
}
return diction
return diction }
}
发布评论