gpt4 book ai didi

ios - 在 Swift 中创建自定义 JSON 映射器

转载 作者:行者123 更新时间:2023-11-28 23:53:14 26 4
gpt4 key购买 nike

这里执行两个任务:

<强>1。将字典转换为模型对象
2.将Model对象转换为Dictionary

写下以下代码并完美运行:

JsonMapper.Swift

class JsonMapper
{
/**
*@Method : decodeUser
*@Param : Dictionary of type [String:Any]
*@ReturnType : User ( which is model )
*@Description: Responsible for mapping Dictionary to Model object
*/
func decodeUser(userDict:[String:Any]) -> User?
{
let decoder = JSONDecoder()
var objUser: User?
do {
let jsonData = try JSONSerialization.data(withJSONObject: userDict, options: JSONSerialization.WritingOptions.prettyPrinted)
objUser = try decoder.decode(User.self, from: jsonData)
print("✅ User Object: \n",objUser)
} catch {
print("❌ Error",error)
}

return objUser ?? User(id: "", type: “”,salary:””)
}

/**
*@Method : encodeUser
*@Param : User
*@ReturnType : Dictionary of type [String:Any]
*@Description: Responsible for mapping Model object User to Dictionary
*/
func encodeUser(modelObj:User) -> [String:Any]
{
let encoder = JSONEncoder()
var objProfileDict = [String:Any]()
do {
let data = try encoder.encode(modelObj)
objUserDict = (try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any])!
print("✅ json dictionary: \n",objProfileDict)
}
catch {
print("❌ Error \(error)")
}

return objUserDict
}

}

用户模型:

struct User:Codable
{
let id : String
let type : String
let salary : String

}

以上代码运行良好,没有问题。

现在的问题是:1.每次我需要将字典转换为任何模型时,在这里您可以看到模型用户是固定的,所以我想将上面的代码转换为通用模型,这样我将传递任何模型,然后它返回结果。

当我传递 Dictionary 时,它应该返回我将在运行时指定的模型,我想使每个模型通用,以便 Dictionary 可以转换为任何指定的模型。

请提供您宝贵的意见。

**注意:1.不想使用任何第三方库,如 ObjectMapper 等。

最佳答案

名称 JsonMapper 在这里具有误导性。您真正的意思是字典映射器。你的方法很好。如果您希望它是通用的,只需传递类型即可。我可能会这样做:

extension JSONDecoder  {
/**
*@Method : decodeUser
*@Param : Dictionary of type [String:Any]
*@ReturnType : User ( which is model )
*@Description: Responsible for mapping Dictionary to Model object
*/
func decode<T: Decodable>(_ type: T.Type, from dictionary: [String: Any]) throws -> T
{
let jsonData = try JSONSerialization.data(withJSONObject: dictionary)
return try decode(T.self, from: jsonData)
}
}

JSONEncoder 也是如此。

关于ios - 在 Swift 中创建自定义 JSON 映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com