intsig171 / SmartCodable

SmartCodable is a data parsing library based on Codable. It is simple to use, with robust compatibility being one of its main features. SmartCodable 是基于Codable实现的数据解析库。简单易用,强悍的兼容性是SmartCodable的主要特点。 表层API和功能几乎和HandyJSON一致,支持快速的迁移。
https://smart-codable.vercel.app
MIT License
417 stars 43 forks source link

使用SmartAny遇到类型转化错误 #24

Closed chuheridangwu closed 5 months ago

chuheridangwu commented 5 months ago

解析数据:

{"code":1,"data":{"index":"4","msg":"上传成功","size":1780},"msg":"success","rid":"Dg0S"}

使用Moya进行网络请求,返回结果中使用泛型的方式进行解析上面的数据

 let jsonString = String(data: moyaResponse.data, encoding: String.Encoding.utf8) ?? ""
guard let data = try? moyaResponse.mapModel(T.self,jsonString: jsonString) else { return }

extension Response{
    func mapModel<T: SmartCodable>(_ type: T.Type, jsonString: String) throws -> T{
        guard let model = type.deserialize(from:jsonString) else { throw MoyaError.jsonMapping(self)}
        return model
    }
}

struct ResponseData<T: SmartCodable>: SmartCodable{
    var code: Int = 0
    var msg: String = ""
    var data: T?
}

崩溃位置,打印了一下value是1780,识别类型错误

    func unbox(_ value: Any, as type: String.Type) throws -> String? {
        guard !(value is NSNull) else { return nil }
        if let tranform = cache.tranform(decodedValue: value, for: codingPath) as? String {
            return tranform
        }
        guard let string = value as? String else {
            throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
        }

        return string
    }
image
intsig171 commented 5 months ago

收到,稍等。

intsig171 commented 5 months ago

image 我这边测试正常。请确认一下使用的版本是否为最新。

如果我误解了你的意思,可以否给一个可运行可复现的代码示例? 可以加一下QQ群号: 865036731。

chuheridangwu commented 5 months ago

崩溃代码

struct ResponseData<T: SmartCodable>: SmartCodable{
    var code: Int = 0
    var msg: String = ""
    var data: T?
}

func request<T: SmartCodable>(model: T.Type, completion:((_ response:T?) -> Void)?){
    let json = """
    {"code":1, "data":{ "index": "4", "msg": " EftI", "size":1780}, "msg": "success", "rid":"DgOS" }
    """
    if let model = model.deserialize(from:json) {
        completion?(model)
    }
}

调用方式

request(model:ResponseData<Dictionary<String,SmartAny>>.self) { response in
    print(response)
}

判断类型那里用is感觉好一点

intsig171 commented 5 months ago

image

我这边测试是正常的。 麻烦确认一下版本是否为3.4.4.

chuheridangwu commented 5 months ago

我理解错了,没有问题,麻烦大佬了