【问题标题】:Check if JSON object null in JWT Authentication for WP REST API检查 WP REST API 的 JWT 身份验证中的 JSON 对象是否为空
【发布时间】:2019-05-01 17:55:15
【问题描述】:

我在 iOS 中使用“JWT Authentication for WP REST API”插件登录我的 wordpress。

当访问凭据正确时,我会收到来自服务器的响应:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbG...",
    "user_email": "test@myhost.com",
    "user_id": 1
}

如果数据不正确,我从服务器得到答案:

{
    "code": "[jwt_auth] incorrect_password",
    "message": "<strong>ERROR</strong>: Incorrect password",
    "data": {
        "status": 403
    }
}

正如我所做的那样检查,例如当数据正确时没有“代码”,如果数据正确则没有“令牌”

我试过了,还是不行

let jsonObject = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

if jsonObject["token"] == nil {
    print("error password")
} else {
}

【问题讨论】:

    标签: json swift jwt


    【解决方案1】:

    首先使用Decodable

    Response 创建为枚举,其中包含successfailure 以及关联类型TokenDataErrorData 的关联类型

    enum Response : Decodable {
    
        case success(TokenData)
        case failure(ErrorData)
    
        init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            do {
                self = try .success(container.decode(TokenData.self))
            } catch DecodingError.keyNotFound {
                self = try .failure(container.decode(ErrorData.self))
            }
        }
    }
    
    struct TokenData : Decodable {
        let token, userEmail : String
        let userId : Int
    }
    
    struct ErrorData : Decodable {
        let code, message : String
    }
    

    let jsonSuccessString = """
    {
    "token": "eyJ0eXAiOiJKV1QiLCJhbG...",
    "user_email": "test@myhost.com",
    "user_id": 1
    }
    """
    
    let jsonFailureString = """
    {
    "code": "[jwt_auth] incorrect_password",
    "message": "<strong>ERROR</strong>: Incorrect password",
    "data": {
    "status": 403
    }
    }
    """
    

    解码 JSON 并打开结果,示例解码两个字符串以进行演示

    let successdata = Data(jsonSuccessString.utf8)
    let failuredata = Data(jsonFailureString.utf8)
    
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
    
        let result1 = try decoder.decode(Response.self, from: successdata)
        switch result1 {
            case .success(let tokenData) : print(tokenData) // TokenData(token: "eyJ0eXAiOiJKV1QiLCJhbG...", userEmail: "test@myhost.com", userId: 1)
            case .failure(let errorData) : print(errorData)
        }
    
        let result2 = try decoder.decode(Response.self, from: failuredata)
        switch result2 {
            case .success(let tokenData) : print(tokenData)
            case .failure(let errorData) : print(errorData) // ErrorData(code: "[jwt_auth] incorrect_password", message: "<strong>ERROR</strong>: Incorrect password")
        }
    } catch {
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 2016-10-06
      • 2021-10-08
      • 2016-04-24
      • 2019-01-01
      • 2019-02-07
      相关资源
      最近更新 更多