【问题标题】:Decode data of Object type and generic type for base JSON response using Decodable使用 Decodable 解码基本 JSON 响应的 Object 类型和泛型类型的数据
【发布时间】:2020-12-17 09:43:26
【问题描述】:

我有一个基本模型 -

struct BaseModel<T:Decodable>: Decodable {
    let jsonData: [T]?
    let status: Bool?
    let message: String?
    
    enum CodingKeys: String, CodingKey {
        case jsonData = "data"
        case status = "success"
        case message
    }
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        do {
            if let string = try container.decodeIfPresent(T.self, forKey: .jsonData) {
                print(string)
                jsonData = [string]
            } else {
                jsonData = nil
            }
        } catch DecodingError.typeMismatch {
            jsonData = try container.decodeIfPresent([T].self, forKey: .jsonData)
        }
        status = try container.decodeIfPresent(Bool.self, forKey: .status)
        message = try container.decodeIfPresent(String.self, forKey: .message)
    }
}

我在 jsonData 下得到两种类型的响应

  1. 对象
  2. 数组

如果我收到作为对象的响应,则在解码时出错。如果我选择 let jsonData: T?,则在解码 Array 响应时遇到问题。

我在我的网络模型中使用这个模型。看起来像-

    func performOperation<T:Decodable>(urlEndPoint: String, method: HTTPMethod, param: Parameters?, isJsonAvailable: Bool, completion: @escaping(_ response: T?, [T]?, String?, Bool?) ->Void) {
        AF.request(urlEndPoint, method: method, parameters: param, headers: header).validate(statusCode: 200..<500).responseDecodable(of: BaseModel<T>.self, decoder: decoder) { (response) in
}

Object情况下的Json响应-

  {
    "success": true,
    "data": {
        "heading": "Same text 1",
        "title": "Sample Text 2",
        "content": "Sample text 3"
    },
    "message": "Api response received"
}

ArrayList情况下的Json响应-

{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Home"
        },
        {
            "id": 2,
            "name": "Profile"
        }
    ],
    "message": "Menu List"
}

【问题讨论】:

  • 显示您的 Object 和您的 Array 类型。同时显示您的 JSON 响应。
  • 另外请发布您从JSONDecode 收到的错误。
  • @gcharita,好像在使用我自己的上述代码????感谢您一直以来的支持。非常感谢,如果我遇到任何问题会告诉你。

标签: swift alamofire codable decodable


【解决方案1】:

您不需要通用结构。如果没有用户数组,只需创建一个可选属性来分配您的对象:


struct BaseModel {
    let data: [User]
    let post: Post?
    let success: Bool
    let message: String
}

struct User: Codable {
    let id: Int
    let name: String
}

struct Post: Codable {
    let heading: String
    let title: String
    let content: String
}

extension BaseModel: Codable  {
    init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            do {
                data = try container.decode([User].self, forKey: .data)
                post = nil
            } catch DecodingError.typeMismatch {
                data = []
                post = try container.decode(Post.self, forKey: .data)
            }
            success = try container.decode(Bool.self, forKey: .success)
            message = try container.decode(String.self, forKey: .message)
        }
}

如果您的帖子中没有显示其他回复,您也可以使用通用结构执行上述相同的方法:

struct BaseModel<T: Codable> {
    let array: [T]
    let element: T?
    let success: Bool
    let message: String
}

extension BaseModel: Codable  {
    init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            do {
                array = try container.decode([T].self, forKey: .array)
                element = nil
            } catch DecodingError.typeMismatch {
                array = []
                element = try container.decode(T.self, forKey: .array)
            }
            success = try container.decode(Bool.self, forKey: .success)
            message = try container.decode(String.self, forKey: .message)
        }
}

【讨论】:

  • 在我当前的代码中它按预期工作,现在我不需要在数组中转换对象类型。谢谢。 @Leo Dabus
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多