这是json错误结构:
{
"jsonrpc": "2.0",
"error": {
"code": "-32700",
"message": "Parse error",
"meaning": "Could not decode token: Error while decoding to JSON: Syntax error"
}
}
这就是成功React结构:
{
"jsonrpc": "2.0",
"result": {
"users": [
{
"id": 371,..... so on data
这里我无法打印错误〉消息在我代码
**代码:**此处可以在case .success(_)
打印语句中打印json响应结果或错误字典,但如何仅打印error > meaning
如何在下面代码中打印错误的"Parse error"
,请指导
class GeneralResponse<T: Codable>: Codable {
var result: T?
let error: ErrorClass?
}
struct ErrorClass: Codable {
let code, message, meaning: String?
}
struct RequestObject {
var params: [String: AnyObject]? = nil
var method: HTTPMethod
var path: String
var isTokenNeed: Bool = false
var vc: UIViewController?
}
class NetworkManager {
private let decoder: JSONDecoder
static let sharedInstance = NetworkManager()
public init(_ decoder: JSONDecoder = JSONDecoder()) {
self.decoder = decoder
}
public func serviceCall<T: Codable>(_ objectType: T.Type,
with request: RequestObject,
completion: @escaping (T?, Error?) -> Void) {
let paramsDict = ["jsonrpc" : "2.0", "params" : request.params ?? nil] as [String : Any?]
AF.request(request.path, method: request.method, parameters: paramsDict as [String : AnyObject], encoding: JSONEncoding.default, headers: "Accept": "application/json")
.responseJSON { response in
switch response.result {
case .success(_):
do {
print("only json respopnse \(response)")
let data = response.data
let responseData = try self.decoder.decode(T.self, from: data ?? Data())
completion(responseData, nil)
} catch {
completion(nil, error)
print("in catch \(error)")
}
case .failure(let AFError):
let error = AFError
print(error.localizedDescription)
print("failure error: \(error)")
}
}
}
}
o/p表示上述调用print("only json respopnse \(response)")
时出错
only json respopnse success({
error = {
code = "-32700";
meaning = "Token Signature could not be verified.";
message = "Parse error";
};
jsonrpc = "2.0";
})
在视图控制器中像这样调用上述方法:
let parameter = ["location": "", "country": "", "gender": "", "keyword": ""] as [String : AnyObject]
let request = RequestObject(params: parameter, method: .post, path: "https://phpwebdevelopment/api/new-user", isTokenNeed: true, vc: self)
NetworkManager.sharedInstance.serviceCall(PostModel.self, with: request) { (response, error) in
}
型号:
struct PostModel: Codable {
let jsonrpc: String?
let result: PostResult?
}
struct PostResult: Codable {
let users: [PostUser]?
}
struct PostUser: Codable {
let id: Int?
}
1条答案
按热度按时间wnavrhmk1#
你没有给我们看你的
Postmodel
,所以我假设它是某种类型的GeneralResponse<T>
类。您应该解码到GeneralResponse类:
现在你可以打印你的错误如果一个存在:
并像这样调用完成处理程序:
主要的本质是不要把
GeneralResponse
作为参数传递给你的函数,而是你所期望的result
类型。例如,你的User
类型如下所示:这样称呼它: