【发布时间】:2018-11-25 00:43:53
【问题描述】:
我正在尝试解析JSON 工作日的日程安排数据,每个工作日都有一系列不同的事件/日程安排重复每个弱点。所以我有一个数据数组,其中包含从周一到周日的工作日对象,而工作日有一系列事件/时间表。
struct Scheduledata: Decodable {
let data: [WeekDay]
}
struct WeekDay: Decodable {
let monday, tuesday, wednesday, thursday, friday, saturday, sunday : [Schedule]?
}
struct Schedule: Decodable {
let id: Int?
let start: String?
let end: String?
let address: String?
let name: String?
let text: String?
let imageURL: String?
let location: CLLocationCoordinate2D?
enum CodingKeys: String, CodingKey {
case text, location, start, end, name, address, id
case imageURL = "image_url"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(Int.self, forKey: .id)
text = try container.decodeIfPresent(String.self, forKey: .text)
imageURL = try container.decodeIfPresent(String.self, forKey: .imageURL)
location = try container.decodeIfPresent(CLLocationCoordinate2D.self, forKey: .location)
start = try container.decodeIfPresent(String.self, forKey: .start)
end = try container.decodeIfPresent(String.self, forKey: .end)
address = try container.decodeIfPresent(String.self, forKey: .address)
name = try container.decodeIfPresent(String.self, forKey: .name)
}
}
extension CLLocationCoordinate2D: Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
self.init()
longitude = try container.decode(Double.self)
latitude = try container.decode(Double.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(longitude)
try container.encode(latitude)
}
}
这是我要解析的 json 对象
{
"data": [
{
"monday": []
},
{
"tuesday": [
{
"id": 1,
"day_id": 2,
"start": "16:30",
"end": "21:00",
"name": "Test Event",
"address": "6 mohamed galal street cairo, heliopolis",
"lat": "30.0866280",
"long": "31.3236130",
"image": "http:\/\/80.211.174.200\/img\/event\/1542547661.jpeg",
"title": "Test_Event",
"description": "This is just a test event to test the testable testi test test testit test............................. yes this is a test indeed",
"created_at": "2018-11-18 15:27:41",
"updated_at": "2018-11-18 15:27:41"
}
]
},
{
"wednesday": []
},
{
"thursday": []
},
{
"friday": []
},
{
"saturday": []
},
{
"sunday": []
}
]
}
我期待的是一本字典:
var schedule = ["monday":[schedule], "tuesday":[schedule], ...]
我得到的似乎是一系列字典。我在每个工作日对象中只有一天,而不是一周中的所有天。
var schedule = [["monday":[schedule], "tuesday":[schedule], ...],["monday":[schedule], "tuesday":[schedule], ...]]
那我该怎么做呢?我每天创建一个不同的结构而不是工作日结构?好像不合逻辑。有些事情是不对的。我确信有一个更智能的解决方案来解析它。
【问题讨论】:
标签: json swift codable decodable