Swift:如何解码来自api的结果,该结果是以字符串或数组字符串的形式返回的? [英] Swift: How to decode result from api which is being returned as a string or as a string of array?

查看:93
本文介绍了Swift:如何解码来自api的结果,该结果是以字符串或数组字符串的形式返回的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSUrlConnection和Apple的Codable库。

I am using NSUrlConnection and Codable library of Apple.

我正在使用Web API为应用程序注册新用户。 API返回状态和消息(在json中,我映射到模型)。

I am using a web API to signup new users for my application. The API returns a status and a message (in json which i map to a model).

这是我的模型类:

Struct SignUpResult {
  let message: String
  let status: String
} 

Struct SignUpParams {
 let name: String
 let email: String
 let mobile_no: String
 let password: String
}

如果用户正确输入了所有参数,则消息将以字符串形式返回。像这样:

If the user gave all the parameters correctly then the message is returned as a string. Like this:

{
    "status": "OK",
    "message": "User signup successfully"
}

另一方面,如果用户输入的参数不正确,则该消息以数组形式返回。像这样:

On the other hand, if the user entered the parameters incorrectly then the message is returned as an array. Like this:

{
    "status": "INVALID_PARAMS",
    "message": [
        "The name may only contain letters."
    ]
}

如果参数不正确,则会出现错误

If the parameters are incorrect then i get the error

"expected to decode a string but found an array instead". 

这是我收到以下错误的代码:

This is the code i get the error on:

let result = JSONDecoder().decode(SignUpResult.self, from: data)

我该怎么办?

推荐答案

我的建议是解码状态作为枚举,并有条件地将消息解码为 String [String] 消息被声明为数组。

My suggestion is to decode status as enum and conditionally decode message as String or [String]. messages is declared as array.

enum SignUpStatus : String, Decodable {
    case success = "OK", failure = "INVALID_PARAMS"
}

struct SignUpResult : Decodable {
    let messages : [String]
    let status: SignUpStatus

    private enum CodingKeys : String, CodingKey { case status, message }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(SignUpStatus.self, forKey: .status)
        switch status {
        case .success: messages = [try container.decode(String.self, forKey: .message)]
        case .failure: messages = try container.decode([String].self, forKey: .message)
        }
    }
}

这篇关于Swift:如何解码来自api的结果,该结果是以字符串或数组字符串的形式返回的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆