数组中的数组Swift 4 Json

时间:2018-11-26 01:12:51

标签: json swift

["?xml": {
    "@encoding" = "utf-8";
    "@version" = "1.0";
}, "root": {
    "@id" = 1;
    date = "11/25/2018";
    message = "";
    station =     (
                {
            abbr = 24TH;
            etd =             (
                                {
                    abbreviation = ANTC;
                    destination = Antioch;
                    estimate =                     (
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 86;
                            direction = North;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 4;
                            platform = 2;
                        },
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 0;
                            direction = North;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 23;
                            platform = 2;
                        },
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 0;
                            direction = North;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 43;
                            platform = 2;
                        }
                    );
                    limited = 0;
                },
                                {
                    abbreviation = DALY;
                    destination = "Daly City";
                    estimate =                     (
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 214;
                            direction = South;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 11;
                            platform = 1;
                        },
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 0;
                            direction = South;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 27;
                            platform = 1;
                        },
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 0;
                            direction = South;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 47;
                            platform = 1;
                        }
                    );
                    limited = 0;
                },
                                {
                    abbreviation = DUBL;
                    destination = "Dublin/Pleasanton";
                    estimate =                     (
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 0;
                            direction = North;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 10;
                            platform = 2;
                        },
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 0;
                            direction = North;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 30;
                            platform = 2;
                        },
                                                {
                            bikeflag = 1;
                            color = BLUE;
                            delay = 0;
                            direction = North;
                            hexcolor = "#0099cc";
                            length = 9;
                            minutes = 50;
                            platform = 2;
                        }
                    );
                    limited = 0;
                },
                                {
                    abbreviation = MLBR;
                    destination = "SFO/Millbrae";
                    estimate =                     (
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 245;
                            direction = South;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 17;
                            platform = 1;
                        },
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 254;
                            direction = South;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 38;
                            platform = 1;
                        },
                                                {
                            bikeflag = 1;
                            color = YELLOW;
                            delay = 0;
                            direction = South;
                            hexcolor = "#ffff33";
                            length = 10;
                            minutes = 53;
                            platform = 1;
                        }
                    );
                    limited = 0;
                }
            );
            name = "24th St. Mission";
        }
    );
    time = "05:28:01 PM PST";
    uri =     {
        "#cdata-section" = "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=24TH&json=y";
    };
}]

要在三个单独的数组中获得缩写,缩写,分钟。因此,根是一个单独的元素,如key1 = xml和key2 = root。 这就是我所拥有的。我正在估算数组,但无法获得我之前提到的值。

static func singleRoute(_ station: String?, completionHandler: @escaping (SingleRouteModel?) -> Void) {
    let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")

    var routeModel = SingleRouteModel()

    URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
        if error == nil {
            do {
                guard let todo = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers)
                    as? [String: Any] else {
                        print("error trying to convert data to JSON")
                        return
                }
                print("todo = \(todo)")
                let root = todo["root"] as? [String: Any]
                let station = root?["station"] as? [[String: Any]]
                var etd: [[String : Any]]?
                var estimate: Any?

                for (_, value) in (station?.enumerated())! {
                    etd = value["etd"] as? [[String: Any]]
                }

                var estimates: [String: Any]? = [:]
                if let etd = etd {
                    for (key, value) in etd.enumerated() {
                        estimates?["\(key)"] = value
                    }
                } else {
                    completionHandler(nil)
                }

                if let estimate = estimates {
                    for (k, v) in estimate {
                        print(v)
                    }
                }

                completionHandler(routeModel)
            } catch  {
                print("error trying to convert data to JSON")
                return
            }
        } else {
            print("no data")
        }
    }.resume()
}

1 个答案:

答案 0 :(得分:1)

这是Playground形式的代码:

import Foundation
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

struct Estimate: Codable {
    let minutes: String
}

struct ETD: Codable {
    let abbreviation: String
    let estimate: [Estimate]
}

struct Station: Codable {
    let abbr: String
    let etd: [ETD]
}

struct Root: Codable {
    let station: [Station]
}

struct SingleRouteModel: Codable {
    let root: Root
}

func singleRoute(_ station: String?, completionHandler: @escaping (SingleRouteModel?) -> Void) {

    let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")

    URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
        if let data = data {
            let model = try? JSONDecoder().decode(SingleRouteModel.self, from: data)
            completionHandler(model)
        }
        else {
            completionHandler(nil)
        }
    }.resume()
}

singleRoute(nil, completionHandler: { model in
    guard let model = model else { print("failed"); return }
    let abbrs = model.root.station
        .map { $0.abbr }
    let abbreviations = model.root.station
        .flatMap { $0.etd }
        .flatMap { $0.abbreviation }
    let minutes = model.root.station
        .flatMap { $0.etd }
        .flatMap { $0.estimate }
        .map { $0.minutes }
    print("abbrs:", abbrs)
    print("abbreviations:", abbreviations)
    print("minutes:", minutes)
})