Invoking REST Web Service – Deserializing JSON Object collection to Anonymous and Strongly typed objects

This article walks through the process of invoking a REST (Representational State Transfer) web service using HttpClient class, deserializing the service response i.e., Json object collection to Anonymous and Strongly typed objects using Json.NET,  then accessing the data in client side using windows console application.

HttpClient:  Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI [Ref: HttpClient class ]

Json.NET:  Open-source high performance JSON framework for Microsoft.Net for converting between .Net objects and JSON.

Microsoft ASP.NET Web API Client Libraries:  Nuget package adds support for formatting and content negotiation to System.Net.Http and support for JSON, XML and form URL encoded data. To install the package run the following package from package manager in Visual Studio.

image

Deserializing JSON object collection to Anonymous type

Below console application source is commented that walks through the process of invoking the REST service, deserializing JSON object collection to anonymous type, accessing data from JSON object using LINQ to JSON,  then accessing JSON data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
//create an instance of HttpClient
HttpClient client = new HttpClient();

//Add DefaultRequestHeader to Json
client.DefaultRequestHeaders.Accept.Add(new  
MediaTypeWithQualityHeaderValue("application/json"));

//Create an instance of HttpResponse,invoke the service 
//asynchronously and store the response
HttpResponseMessage response = 
client.GetAsync("https://ebanking.bankofmaldives.com.mv/xe/").Result;
            
//Http Status code 200
if (response.IsSuccessStatusCode)
{
//Read response content result into string variable
string strJson = response.Content.ReadAsStringAsync().Result;
//Deserialize the string to JSON object
dynamic jObj = (JObject)JsonConvert.DeserializeObject(strJson);
   
//access items and add to the list - LINQ to JSON
var result = jObj["CurrencyList"].Select(item => new
                {
                   key = item["Key"],
                   code = item["Value"]["Code"],
                   description = item["Value"]["Description"],
                   buy = item["Value"]["Buy"],
                   sell = item["Value"]["Sell"],
                }).ToList();

                //output the data 
                foreach (var item in result)
                {
Console.WriteLine(item.key + "--" + item.code + "" + 
item.description + item.buy + item.sell);
                }
            }
        }

    }
}

 

Deserializing JSON object collection to Strong type

Below console application source is commented that walks through the process of invoking the REST service, deserializing JSON object collection to strong types and accessing data from strong type.

Json2csharp: When JSON or URL to JSON (Web Service URI) is entered json2csharp.com generates C# classes. [Refer  json2charp.com ]

Json2csharp is used to generate the classes from JSON that is returned from the web service URI https://ebanking.bankofmaldives.com.mv/xe/ 

//**Note: Below classes are generated by utilising //http://json2csharp.com/
//Of course these can be hand coded by looking at the Json response from the service**

        public class Value
        {
            public string Code { get; set; }
            public string Description { get; set; }
            public double Buy { get; set; }
            public double Sell { get; set; }
        }

        public class CurrencyList
        {
            public string Key { get; set; }
            public Value Value { get; set; }
        }

        public class RootObject
        {
        public List<CurrencyList> CurrencyList { get; set; }
        }
        

Below provided source is rest of the implementation of the client application.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
//Create an instance of HttpClient instance
HttpClient client = new HttpClient();
                        
//Set Request Header
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));

//Create an instance of HttpResponse, invoke the service

//asynchronously and store the response

HttpResponseMessage response = 
client.GetAsync("https://ebanking.bankofmaldives.com.mv/xe/").Result;
            
            
if (response.IsSuccessStatusCode)
            {

string strJson = response.Content.ReadAsStringAsync().Result;
//Deserialize to strongly typed class i.e., RootObject
RootObject obj = JsonConvert.DeserializeObject<RootObject>(strJson);

//Iterate through the list and access data
foreach (CurrencyList currencyItem in obj.CurrencyList)
{
                Console.WriteLine(currencyItem.Key + "-" + currencyItem.Value.Code + "-" + currencyItem.Value.Description + 
"-"+ currencyItem.Value.Buy + "-" + currencyItem.Value.Sell);
                    
}

}
}
}
}

 

References

Below video presentation is from Peter Smith at Build 2013 event on HttpClient

No Comments