Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
处理json响应可观察swift_Swift_Rx Swift_Swifty Json_Codable_Moya - Fatal编程技术网

处理json响应可观察swift

处理json响应可观察swift,swift,rx-swift,swifty-json,codable,moya,Swift,Rx Swift,Swifty Json,Codable,Moya,我有一个使用SwiftyJSON的应用程序,它可以正常工作。然而,我现在想扩展项目并重构代码,但我有一点问题,因为我现在切换到Codable,我需要能够从任何路径而不是硬编码路径映射JSON。目前,我的jsonResponse如下所示 /// handle the network response and map to JSON /// - returns: Observable<JSON> func handleResponseMapJSON() -> Obs

我有一个使用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
///-回报:可观察
func handleResponseMapJSON()->可观察{
返回self.map{representor in
警卫let response=代表?Moya.其他响应{
返回失败(或错误或提示)
}
防护((200…299)~=响应.状态码)其他{
return.failure(ORMError.ORMNotSuccessfulHTTP)
}
guard let json=json.init(rawValue:response.data),
json!=json.null,
让code=json[“code”].int-else{
return.failure(ORMError.ORMParseJSONError)
}
保护代码==BizStatus.BizSuccess.rawValue else{
let消息:字符串={
让json=json.init(数据:response.data)
guard let msg=json[“status”]。字符串else{return”“}
返回消息
}()
日志(消息,.error)
return.failure(orError.ORMBizError(resultCode:\(code)”,resultsg: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)
        }
    }
}

在上面的例子中,结果将是一个可观察的

我建议您尝试以下方法:

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)
        }
    }
}

在上面的例子中,结果将变成一个可观察的

我想对
PrimitiveSequenceType
进行扩展,将其视为
单个

import Foundation
import RxSwift
import Moya

 public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementType == Response {
    func map<T>(_ type: T.Type, using decoder: JSONDecoder? = nil) -> PrimitiveSequence<TraitType, T> where T: Decodable {
        return self.map { data -> T in
            let decoder = decoder ?? JSONDecoder()
            return try decoder.decode(type, from: data.data)
        }
    }
}

我想对
PrimitiveSequenceType
进行扩展,将其视为
Single

import Foundation
import RxSwift
import Moya

 public extension PrimitiveSequenceType where TraitType == SingleTrait, ElementType == Response {
    func map<T>(_ type: T.Type, using decoder: JSONDecoder? = nil) -> PrimitiveSequence<TraitType, T> where T: Decodable {
        return self.map { data -> T in
            let decoder = decoder ?? JSONDecoder()
            return try decoder.decode(type, from: data.data)
        }
    }
}

这会在参数类型“User.type”中引发错误
,“User”不符合预期的类型“ResponseType”
我创建了一个要点,其中包含使用
swiftyJson
的代码以及我试图实现的可编码项将用户符合ResponseType,或者创建一个符合ResponseType的新类型,并将用户作为其结果类型。这会在参数类型中引发一个错误
“User.Type”,“User”不符合预期的类型“ResponseType”
我创建了一个要点,其中包含使用
swiftyJson
的代码以及我试图实现的代码。请将用户与ResponseType一致,或创建一个符合ResponseType的新类型,并将用户作为其结果类型。我希望解决此错误并将成功值传递给extensionI已经创建了一个要点,其中包含带有
swiftyJson
的代码和我正在尝试实现的代码。您已经使用了RxSwift,它为您带来了错误。对于结果,您可以在type方法的type中指定它。如果你想做一个自定义错误检查,你可以用一个新方法做类似上面提到的事情
filterServerError
任何你喜欢的名字,然后简单地在那里抛出错误,RxSwift将为你携带它,让订阅者接收。我想解决错误并在扩展中传递成功值。我已经创建了一个gist包含带有
swiftyJson
的代码,以及我试图实现的代码。您已经在使用RxSwift,它会为您带来错误。对于结果,您可以在type方法的type中指定它。如果您想进行自定义错误检查,您可以使用一个新方法
filterServerError
执行与上面提到的类似的操作,您可以选择任何您喜欢的名称,然后简单地在那里抛出错误,RxSwift将为您带来错误,以便订阅者接收。