Search code examples
c#jsondictionarylistiterator

How to iterate over a list dictionaries and print their content?


I am a c# newbie and I figured out to get a response from an API using HttpClient and with the following code I got the JSON from the server shown below:

class Program
{
    public class Parameter
    {
        public Usuario Usuario { get; set; }
        public Establecimiento Establecimiento { get; set; }
    }
    public class Usuario
    {
        public string email { get; set; }
        public string password { get; set; }
    }

    public class Establecimiento
    {
        public int id { get; set; }
    }

    public class deliveryData
    {
        public string id { get; set; }
        public string establecimiento_id { get; set; }
        public string numero_orden { get; set; }
        public string ciudad_id { get; set; }
        public string fecha { get; set; }
    }

    static void Main()
    {
        try
        {
            RunAsync().Wait();
            Console.ReadLine();
        }
        catch (AggregateException e)
        {
            Console.WriteLine("Exception details: " + e.ToString());
            Console.ReadLine();
        }
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://it-215...web.development.co/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // HTTP POST
                var json = new Parameter
                {
                    Establecimiento = new Establecimiento
                    {
                        id = 147
                    },
                    Usuario = new Usuario
                    {
                        email = "user@email.com",
                        password = "something"
                    }
                };

                HttpResponseMessage response = await client.PostAsJsonAsync("api/service", json);
                response.EnsureSuccessStatusCode();    // Throw if not a success code.
                string responseBodyAsText;
                responseBodyAsText = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBodyAsText);

                //List<Dictionary<string, deliveryData>> decodedDeliveries = JsonConvert.DeserializeObject<List<Dictionary<string, deliveryData>>>(responseBodyAsText);

                //foreach (var delivery in decodedDeliveries)
                //{
                //    Console.WriteLine(delivery.ToString());
                //}

            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("Exception details: " + e.ToString());
            }
        }
    }
}

JSON response until here:

[   {
    "PedidosOnline": {
      "id": "7491031",
      "establecimiento_id": "147",
      "numero_orden": "1769629-20160509211442",
      "fecha": "2016-05-09 21:14:42"
    }   
    },   {
    "PedidosOnline": {
      "id": "7491328",
      "establecimiento_id": "147",
      "numero_orden": "1559397-20160509212644",
      "fecha": "2016-05-09 21:26:44"
    }   
} ]

Now when I comment the

Console.WriteLine(responseBodyAsText);

and uncomment the decoding line and the foreach, this is what I get:

System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData]
System.Collections.Generic.Dictionary`2[System.String,ProjectName.Program+deliveryData]

What I want is to get a clean print of the fields viewed in the JSON, since my next step is to save every field of the dictionaries in an Access DB (which I've no idea how to do but I'll figure it out). So I need a little help with this, any advice will be much apprecated.

Many thanks in advance.


Solution

  • Instead of printing the Dictionary objects themselves, loop through each Dictionary and print every key-value pair.

    List<Dictionary<string, deliveryData>> decodedDeliveries = JsonConvert.DeserializeObject<List<Dictionary<string, deliveryData>>>(responseBodyAsText);
    
    foreach (var delivery in decodedDeliveries)
    {
      foreach(var pair in delivery) {
        Console.WriteLine(pair.Key + " : " + pair.Value);
      }
    }