快速编码与动态键



我的JSON结构为:

"periods": {
"2018-06-07": [
{
"firstName": "Test1",
"lastName": "Test1"
}
],
"2018-06-06": [
{
"firstName": "Test1",
"lastName": "Test1"
}
]
}

我试图像这样解析它:

public struct Schedule: Codable {
public let periods: Periods
}
public struct Periods: Codable {
public let unknown: [Inner]
public struct Inner: Codable {
public let firstName: String
public let lastName: String
}
private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
self.unknown = try container.decode([Inner].self, forKey: CustomCodingKeys(stringValue: "2018-06-06")
}
}

但是我只能得到一个值(2018-06-06)的结果。我这里有多个日期要解析。这可能吗?

假设您省略了围绕此块的{},并且这是有效 JSON 所必需的,以下是解析内容的最简单解决方案,您真的根本不需要处理CodingKey,因为您的名字与 JSON 中的键匹配,因此合成CodingKey可以正常工作:

public struct Schedule: Codable {
public let periods : [String:[Inner]]
}
public struct Inner: Codable {
public let firstName: String
public let lastName: String
}
let schedule = try? JSONDecoder().decode(Schedule.self, from: json)
print(schedule?.periods.keys)
print(schedule?.periods["2018-06-07"]?[0].lastName)

关键是外部 JSON 是具有单个键的 JSON 对象(字典/映射(,periods该键的值是数组的另一个映射。 就像这样分解它,一切都会自动消失。

好的,所以我是这样想出来的:

public struct Schedule: Codable {
public let periods: Periods
}
public struct Periods: Codable {
public var innerArray: [String: [Inner]]

public struct Inner: Codable {
public let firstName: String
public let lastName: String
}

private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)

self.innerArray = [String: [Inner]]()
for key in container.allKeys {
let value = try container.decode([Inner].self, forKey: CustomCodingKeys(stringValue: key.stringValue)!)
self.innerArray[key.stringValue] = value
}
}
}

结果我得到了这样的字典:["2018-06-06": [Inner]]键是这个日期字符串,值 Inner。

我认为 JSON 应该在开头附加{,在末尾附加}才能成为有效的 JSON,然后您可以使用这样的代码轻松提取句点:

struct Period: Decodable {
let firstName: String, lastName: String
}
let schedule = try? JSONDecoder().decode([String:[String:[Period]]].self, from: jsonData!)
let periods = schedule?.values.first?.values

相关内容

  • 没有找到相关文章

最新更新