检查WP REST API的JWT身份验证中的JSON对象是否为空

时间:2019-05-01 17:55:15

标签: json swift jwt

我正在使用“ JWT Authentication for WP REST API”插件在iOS中登录我的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 {
}

1 个答案:

答案 0 :(得分:0)

首先使用Decodable

使用案例Responsesuccess以及关联的类型failureTokenData

创建ErrorData作为枚举

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