首页 > 解决方案 > 处理 json 中接收的字符串和 int

问题描述

我有一个看起来像这样的json...

{
    id = 123456;
    isDeleted = 0;
    name = testName;
    parentId = "<null>"; // This can also be integer
    plantId = 1223;      // This can also be string 
    type = 1;
}

parentId在上面的响应中,我可以为&获得一个字符串或一个 int plantId。我该如何处理这两种情况..?

这就是我的结构的样子......

struct Root : Decodable {
    let organizations : [Organization1]
}

struct Organization1 : Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: Int?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?


}

标签: iosjsonswift

解决方案


你可以这样做

struct GeneralProduct: Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: String?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?


    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        isDeleted = try container.decode(Bool.self, forKey: .isDeleted)
        name = try container.decode(String.self, forKey: .id)
        type = try container.decode(Int.self, forKey: .type)
        loggedInUserId = try container.decode(Int.self, forKey: .loggedInUserId)

        if let value = try? container.decode(Int.self, forKey: .parentId) {
            parentId = String(value)
        } else {
            parentId = try container.decode(String.self, forKey: .id)
        }

        if let value = try? container.decode(Int.self, forKey: .plantId) {
                   plantId = String(value)
               } else {
                   plantId = try container.decode(String.self, forKey: .id)
               }
    }


}

推荐阅读