gpt4 book ai didi

ios - 解析动态 JSON 的模型

转载 作者:行者123 更新时间:2023-11-28 11:29:50 26 4
gpt4 key购买 nike

我正在访问一个可能会返回两个不同 JSON 之一的端点,具体取决于用户是否需要回答安全问题:

// possible response (payload) #1
{
"token": "123lknk123kj1n13132"
}

// possible response (payload) #2
{
"securityQuestion": "What is your mother's maiden name?"
}

我的目标是创建一个模型,该模型将根据负载中存在的 key (即 “token”“securityQuestion”)以不同方式解码 JSON . 目前,我遇到了一个解析错误,我不知道为什么。

我从对上一个关于 SO 的问题的精心设计的回答中获得灵感。 .我当前的代码是它的修改版本(理论上)符合我的需要。我希望我的代码的最终版本保留这种结构。我的代码如下:

/**
Enumerates the possible payloads received from Server

- success: Successful payload that contains the user's access token
- securityQuestion: Payload that contains the security question that the user has to answer to receive a token
*/
enum PayloadType: String, Decodable {
case success
case securityQuestion
}

protocol Payload: Decodable { static var payloadType: PayloadType { get } }

/// Model for successful response sent by the server.
struct SuccessfulResponse: Payload {
static let payloadType = PayloadType.success
let token: String
}

/// Model for response sent by the server which includes a security question
struct SecurityQuestionResponse: Payload {
static let payloadType = PayloadType.securityQuestion
let securityQuestion: String
}

/// Model for building a response sent by the server.
struct Response: Decodable {
let data: Payload
let payloadType: PayloadType

init(from decoder: Decoder) throws {
// NOTE*: This part is a little shaky, maybe this is where I am going wrong
let values = try decoder.container(keyedBy: CodingKeys.self)
self.payloadType = try values.decode(PayloadType.self, forKey: .payloadType)

// payloadType will determine how the JSON is decoded
switch self.payloadType
{

case .success:
self.data = try values.decode(SuccessfulResonse.self, forKey: .data)

case .securityQuestion:
self.data = try values.decode(SecurityQuestionResponse.self, forKey: .data)
}
}

private enum CodingKeys: String, CodingKey {
case data
case payloadType
}
}

在发布这个问题之前,我查看了各种类似的帖子( 123 ),但没有一个真正符合需要。

最佳答案

我想建议一种不同的方法,不是更简单但更易于使用,至少对我来说更清楚。

struct Token: Codable { 
let token: String?
}

struct SecurityQuestion:Codable {
let securityQuestion: String?
}

在请求函数中添加以下内容

URLSession.shared.dataTask(with: url, completionHandler: {data,response,error in

do {
let responseObject = try JSONDecoder().decode(Token.self, from: data!)

let token = responseObject.token
print(token)
} catch let parseError {
print(parseError)
do{
let responseObject = try JSONDecoder().decode(SecurityQuestion.self, from: data!)
let securityQuestion = responseObject.securityQuestion
print(securityQuestion)
}catch{
print(error)
}
}
})

主要思想是使用 catch block 尝试另一种解码类型,因为第一个解码类型失败,如果您有许多不同的响应,您可以做更多的 catch block 来执行新的解码类型,

关于ios - 解析动态 JSON 的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com