Swift JSON需要跳过一个组并获取其子元素

时间:2017-09-01 19:00:11

标签: json swift

您好我正在尝试在swift 3中解析此JSON并且有一个具有变量键的组的对象。我想知道如何跳过此元素并访问其子元素以用于创建JSON对象。 a json snippet showing code that i want to edit

我正在做类似

的事情
init(JSON: [String: Any]){
    eventTime = JSON["eventTime"] as? String ?? "" 
    eventId = JSON["eventID"] as? String ?? ""
    .
    .
    .
  }

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

迟早你要更新到Swift 4,所以这就是答案(使用自定义日期格式化程序):

// eventTime as String (not parsed)
struct Event: Decodable {
    let id: String
    let time: String
    let headerText: String
    let zones: [String]
    let text: [String]

    enum CodingKeys: CodingKey, String {
        case id = "eventId"
        case time = "eventTime"
        case headerText = "eventHeaderText"
        case zones
        case text
    }
}

// eventTime parsed as Date
struct DatedEvent: Decodable {
    let id: String
    let date: Date
    let headerText: String
    let zones: [String]
    let text: [String]

    static let formatter: DateFormatter = {
        $0.dateFormat = "hh:mm a zzz EEEE dd MMMM yyyy"
        $0.locale     = Locale(identifier:"en_US_POSIX")
        return $0
    }(DateFormatter())

    enum CodingKeys: String, CodingKey {
        case id = "eventId"
        case date = "eventTime"
        case headerText = "eventHeaderText"
        case zones
        case text
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        id = try container.decode(String.self, forKey: .id)

        let rawDate = try container.decode(String.self, forKey: .date)
        if let parsedDate = DatedEvent.formatter.date(from: rawDate) {
            date = parsedDate
        } else {
            let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Date is encoded in an unexpected format.")
            throw DecodingError.dataCorrupted(context)
        }

        headerText = try container.decode(String.self, forKey: .headerText)
        zones = try container.decode([String].self, forKey: .zones)
        text = try container.decode([String].self, forKey: .text)
    }
}

let jsonData = """
{
    "Statements" : {
        "Some Random Date" : {
            "eventTime" : "08:37 PM GMT Friday 01 September 2017",
            "eventId" : "bbb",
            "eventHeaderText" : "ccc",
            "zones" : [
                "Cali"
            ],
            "text" : [
                "hi",
                "lorem"
            ]
        }
    }
}
""".data(using: .utf8)!

let dec = try! JSONDecoder().decode([String:[String:DatedEvent]].self, from: jsonData)
dump(dec)