Paolo Gdf
Paolo Gdf

Reputation: 759

SwiftyJSON parse json query

I am writing a code in swift 3 for parse a query in json format result from http request.

the json format is:

JSON: {
base = stations;
coord =     {
    lat = "23.9";
    lon = "42.89";
};
weather =     (
            {
        description = mist;
        icon = 50n;
        id = 701;
        main = Mist;
    },
            {
        description = fog;
        icon = 50n;
        id = 741;
        main = Fog;
    }
);
wind =     {
    deg = "222.506";
    speed = "1.72";
};}

My code is:

Alamofire.request(url).responseJSON { response in

        if let a = response.result.value  {

            let jsonVar = JSON(a)

            if let resDati = jsonVar["base"].string {
                print(resDati as String)  // <- OK
            }

            if let dati2 = jsonVar["weather"].array {

                for item in dati2 {

                    print(" > \(item["main"])") // <- OK

                }

            }

        } else {
            print(Error.self)
        }

    }

The problem is on "coord" and "wind" data i have try:

if let dati4 = jsonVar["wind"].array {

    for item in dati4 {

        print("-- \(item)")

    } }

I cannot print the data relatives to "wind" and "coord" in json format.

How can I resolve this.

Thank you.

Upvotes: 1

Views: 138

Answers (1)

vadian
vadian

Reputation: 285260

The key wind contains a dictionary, not an array, you can get the deg and speed values using SwiftyJSON with this code:

if let wind = jsonVar["wind"].dictionary,
    let deg = wind["deg"]?.double,
    let speed = wind["speed"]?.double {
    print(deg, speed)
}

coord works accordingly

if let coord = jsonVar["coord"].dictionary,
    let lat = coord["lat"]?.double,
    let lon = coord["lon"]?.double {
    print(lat, lon)
}

Note: All values are of type Double, the json format is misleading.

Upvotes: 2

Related Questions