ios - 处理 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?
}
解决方案
你可以这样做
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)
}
}
}
推荐阅读
- python - 在字典列表中,根据键合并列表
- c - 如何按数组对c中的名称进行排序
- ruby - splat 运算符在应用于范围表达式时如何理解?
- google-cloud-platform - Cloud Tasks 条件执行
- maven - 如何允许结果
在 Kotlin 中作为返回类型? - python - 如何在python的字符串中添加空格作为参数?
- java - Activiti APS 的 Java 和 MySQL 内存配置问题
- amazon-web-services - 在 CN 之外顺利使用 AWS CN
- ios - 顶部的自定义 TabBar
- java - 我可以将 JWT 授权从 spring RestController 传递给外部后端 API