【问题标题】:Handle string and int received in json [duplicate]处理 json 中收到的字符串和 int [重复]
【发布时间】:2020-06-03 07:57:51
【问题描述】:

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

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

在上面的响应中,我可以得到parentIdplantId 的字符串或整数。我该如何处理这两种情况..?

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

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?


}

【问题讨论】:

  • 能分享一下解析代码吗?
  • 你可以尝试String(x)进行解析。当 x 的类型为 StringInt 时,它将起作用。
  • 我没有正确理解@pawello2222...您是否介意详细解释一下...?

标签: ios json swift


【解决方案1】:

你可以这样做

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


}

【讨论】:

  • 但是我怎样才能在我的结构本身内进行更改@jawadAli..?在这里,您似乎已经用Codable struct 给出了答案,而我使用了Decodable
  • Decodable更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2016-03-29
  • 2013-09-14
相关资源
最近更新 更多