“Get out from smog” – parsing JSON

“Get out from smog” part II

Today I will focus on parsing data from JSON.

Service http://powietrze.gios.gov.pl provides information on air quality in this format. So I would use this information in my application. In the first step I need to download it.

Use to this – webClient class to dowload string from website and additionally, need to set encoding to UTF8 to have the Polish special characters.

var webClient = new System.Net.WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
var json = webClient.DownloadString(@"http://powietrze.gios.gov.pl/pjp/current/getAQIDetailsList?param=AQI");

Next, I parses JSON to the materialized object like list, which got two properites:

public string stationLocation {  get; private set; }
public List<Dictionary<string, string>> listMeasurements { get; private set; }

To parse JSON i use Newtonsoft Json.

var arrayJson = JArray.Parse(json);
List<ParseJsonToList> model = new List<ParseJsonToList>();
foreach (JObject root in arrayJson)
{
    List<Dictionary<string, string>> valuesList = new List<Dictionary<string, string>>();
    var valuesMeasurements = JObject.Parse(root["values"].ToString());
    foreach (var item2 in valuesMeasurements)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        dictionary.Add(item2.Key, item2.Value.ToString());
        valuesList.Add(dictionary);
    }
    model.Add(new ParseJsonToList()
    {
        stationLocation = root["stationName"].ToString(),
        listMeasurements = valuesList
    });
}

After parsing as you see I have 162 count places where air quality is measured.

json parse

Also if you like dynamic you can write your parse code like this:

dynamic api = JArray.Parse(json);
dynamic check = JsonConvert.DeserializeObject(json);
List<ParseJsonToList> model = new List<ParseJsonToList>();
foreach (var value2 in check)
{
    List<Dictionary<string, string>> valuesList = new List<Dictionary<string, string>>();
    foreach (var item in value2.values)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        var dynamicName = item.Name;
        var dynamicValue = item.Value.ToString();
        dictionary.Add(dynamicName, dynamicValue);
        valuesList.Add(dictionary);
    }
    model.Add(new ParseJsonToList()
    {
        stationLocation = value2.stationName,
        listMeasurements = valuesList
    });
}

Both code return exacly the same data. Code based on dynamic looks more clear but without strong typing.

In next episode I’ll try to get longitudes of measuring stations.

Link to the project : here

Leave a Reply

Your email address will not be published. Required fields are marked *