John Sullivan
John Sullivan

Reputation: 90

Embedded json data in swift three levels

I am having some troubles with some json data. I'm making a weather app and most of the information I parsed works but the weather

this is the council output for the json data as a whole this is the section im having troubles with

the full output of json

{
base = stations;
clouds =     {
    all = 90;
};
cod = 200;
coord =     {
    lat = "39.74";
    lon = "-104.98";
};
dt = 1427305893;
id = 5419384;
main =     {
    humidity = 84;
    pressure = 1022;
    temp = "274.07";
    "temp_max" = "275.35";
    "temp_min" = "272.15";
};
name = Denver;
rain =     {
    1h = "0.25";
};
snow =     {
    1h = "0.17";
};
sys =     {
    country = US;
    id = 532;
    message = "0.07829999999999999";
    sunrise = 1427288058;
    sunset = 1427332632;
    type = 1;
};
visibility = 4023;
weather =     (
            {
        description = "light rain";
        icon = 10d;
        id = 500;
        main = Rain;
    },
            {
        description = snow;
        icon = 13d;
        id = 601;
        main = Snow;
    },
            {
        description = fog;
        icon = 50d;
        id = 741;
        main = Fog;
    },
            {
        description = mist;
        icon = 50d;
        id = 701;
        main = Mist;
    }
);
wind =     {
    deg = 20;
    gust = "14.9";
    speed = "12.9";
};

} i also have it print the keys

[base, id, dt, snow, main, coord, sys, wind, weather, visibility, clouds, cod, name, rain]

I tried to save it as an array but when I set the arry[0] to a string it crashes

my code for the function

 func populateLabels(weatherData: NSData){

    var jsonError: NSError?

    let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) as NSDictionary
  println(json)

    if let city = json["name"] as? String {

        CityName.text = city
    }
    println(json.allKeys)

    if let coord = json["coord"] as? NSDictionary {

        if let longi = coord["lon"] as? Double {
            long.text = String(format: "%.2f", longi)
        }

        if let lati = coord["lat"] as? Double {
            lat.text = String(format: "%.2f", lati)
        }

    }

    if let main = json["main"] as? NSDictionary {

        if let temper = main["temp"] as? Double {
            temp.text = String(format: "%.2f", temper)
        }


    }

If anyone knows how to get to the description that would be awesome thanks js

Upvotes: 0

Views: 80

Answers (1)

John Sullivan
John Sullivan

Reputation: 90

I got it.. thanks for the help blacksquare, larme, chirag90

if let tasks = json["weather"] as? NSArray
    {
        if let task = tasks[0] as? NSDictionary
        {
            if let taskName = task["description"] as? NSString
            {
                println(taskName)
            }
        }
    }

Upvotes: 1

Related Questions