swift - 处理 json 响应 Observable swift
问题描述
我有一个使用 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[""]
值的通过。任何帮助表示赞赏
解决方案
我建议你尝试这样的事情:
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>>
推荐阅读
- python-3.x - “冻结”未定义Pylance(reportUndefinedVariable)
- c - 使用 C 使用 Windows 读取传入的串行数据
- fluid-framework - 尝试在根 SharedDirectory 中存储 SharedString 时未注册通道工厂
- bash - Bash: -e 选项从 $@ 消失了
- haskell - 在 Haskell 上过滤字符
- r - R:使用 table() 时未出现的功能名称
- c++ - 将图像数据保存到 sqlite
- python - Python程序被Windows Defender阻止
- git - Visual Studio Team Explorer GitHub - 当你有两个遥控器时,你如何指定一个用于传出提交?
- junit - 如何在不创建新测试的情况下导入 Jira X-Ray 数据