gpt4 book ai didi

swift - 快速处理 json 响应 Observable

转载 作者:行者123 更新时间:2023-11-28 07:27:40 25 4
gpt4 key购买 nike

我有一个使用 SwiftyJSON 并且可以运行的应用程序。然而,我现在想扩展项目并重构代码,但我遇到了一些问题,因为我现在切换到 Codable 并且我需要能够从任何路径而不是硬编码路径映射 JSON。目前我的 jsonResponse 看起来像这样

/// handle the network response and map to JSON
/// - returns: Observable<JSON>
func handleResponseMapJSON() -> Observable<Result<JSON, ORMError>> {

return self.map { representor in

guard let response = representor as? Moya.Response else {
return .failure(ORMError.ORMNoRepresentor)
}

guard ((200...299) ~= response.statusCode) else {
return .failure(ORMError.ORMNotSuccessfulHTTP)
}

guard let json = JSON.init(rawValue: response.data),
json != JSON.null,
let code = json["code"].int else {
return .failure(ORMError.ORMParseJSONError)
}

guard code == BizStatus.BizSuccess.rawValue else {
let message: String = {
let json = JSON.init(data: response.data)
guard let msg = json["status"].string else { return "" }
return msg
}()
log(message, .error)
return .failure(ORMError.ORMBizError(resultCode: "\(code)", resultMsg: message))
}

return .success(json["result"])

}
}

我如何消除硬编码 json[""] 值的 channel 。感谢任何帮助

最佳答案

我建议你尝试这样的事情:

protocol ResponseType: Codable {
associatedtype ResultType
var status: String { get }
var code: Int { get }
var result: ResultType { get }
}

func handleResponseMap<T, U>(for type: U.Type) -> (Any) -> Result<T, ORMError> where U: ResponseType, T == U.ResultType {
return { representor in
guard let response = representor as? Moya.Response else {
return .failure(.ORMNoRepresentor)
}
guard ((200...299) ~= response.statusCode) else {
return .failure(.ORMNotSuccessfulHTTP)
}
return Result {
try JSONDecoder().decode(U.self, from: response.data)
}
.mapError { _ in ORMError.ORMParseJSONError }
.flatMap { (response) -> Result<T, ORMError> in
guard response.code == BizStatus.BizSuccess.rawValue else {
log(response.status, .error)
return Result.failure(ORMError.ORMBizError(resultCode: "\(response.code)", resultMsg: response.status))
}
return Result.success(response.result)
}
}
}

然后您可以直接映射到您的 Codable 类型:

let result = self.map(handleResponseMap(for: MyResponse.self))

在上面,结果最终会是一个 Observable<Result<ResultType, ORMError>>

关于swift - 快速处理 json 响应 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55955387/

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