Using JSON.NET With ASP.NET API

Introduction

In this article, there is a description of JSON.NET with the ASP.NET Web API.  JSON.NET is a framework that has many features and it uses Java Script Object Notation (JSON). Some features of this are not supported by the DataContractJSONSerializer.

Features

JSON.Net has the following features:

  • Has a flexible JSON serializer that converts .NET objects and JSON
  • Has high performance that is faster than .Net's build in JSON serializer
  • Converts JSON to XML and XML to JSON
  • Supported by Windows 8, Silverlight, Windows Phone, . NET 3.5 and .NET 4

A set of open-ended formatters that can be supported by the ASP. Net Web API Beta, to read and write the data to and from any media type that can be supported by you. Let's see an example. The vCard Format that has text media type or vCard Media type, that you want to support then write the formatter and register it for the media type.

Build the formatter

Here we give the code of sample of formatter that supports reading an writing content of the media type. An it is derived from the MediaTypeFormatter Class.

  1. public class Json_Format : MediaTypeFormatter  
  2. {  
  3.     private Json_Serializer _json_Serializer;  
  4.     public Json_Format (Json_Serializer json_Serializer)  
  5.     {  
  6.         _json_Serializer = json_Serializer ?? new Json_Serializer();  
  7.         SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));  
  8.         encoding = new UTF8encoding(falsetrue);  
  9.     }  
  10.     protected override bool Can_ReadType(Type _type)  
  11.     {  
  12.         if (type == typeof(IKeyValueModel))  
  13.         {  
  14.             return false;  
  15.         }  
  16.             return true;  
  17.         }  
  18.         protected override bool Can_WriteType(Type _type)  
  19.         {  
  20.             return true;  
  21.         }  
  22.         protected override Task<object> OnReadFromStream(Type _type, Stream _stream, HttpContentHeaders content_Headers, FormatterContext formatter_Context)  
  23.         {  
  24.             Json_Serializer s_serializer = Json_Serializer.Create(_json_Serializer);  
  25.             return Task.Factory.StartNew(() =>  
  26.             {  
  27.                 using (StreamReader stream_Read = new StreamReader(_stream, encoding))  
  28.                 {  
  29.                     using (JsonTextReader json_TextRead = new JsonTextReader(stream_Read))  
  30.                     {  
  31.                         return s_serializer.Deserialize(json_TextRead, _type);  
  32.                     }  
  33.                 }  
  34.             });  
  35.         }  
  36.         protected override Task OnWriteToStream(Type _type, object _value, Stream _stream, HttpContentHeaders content_Headers, FormatterContext formatter_Context, TransportContext transport_Context)  
  37.         {  
  38.             Json_Serializer s_serializer = Json_Serializer.Create(_json_Serializer);  
  39.             return Task.Factory.StartNew(() =>  
  40.             {  
  41.                 using (StreamWriter stream_Write = new Stream_Write(_stream, encoding))  
  42.                 {  
  43.                     using (JsonTextWriter json_TextWrite = new JsonTextWriter(stream_Writer))  
  44.                     {  
  45.                         s_serializer.Serialize(jsonTextWriter, _value);  
  46.                     }  
  47.                 }  
  48.             });  
  49.         }  
  50.     }  
  51. } 

Build the Sample of APIController

Now we create a sample of API controller.  In  it we create a type that is not serialized with DataContractJSONSerializer.

  1. public class Home_Control : ApiController  
  2. {  
  3.     public HomeInfo Get()  
  4.     {  
  5.         return new HomeInfo();  
  6.     }  
  7. }  
  8. public class Home_Info  
  9. {  
  10.     private readonly DateTime created = DateTim._UtcNow;  
  11.     private readonly Dictionary<intstring> _cityMap = new Dictionary<intstring>  
  12.     {  
  13.         { 1, "Delhi"},  
  14.         { 2, "Nodia" },  
  15.         { 3, "Agra" },  
  16.         { 4, "Lucknow" },  
  17.     };  
  18.     public DateTime Created { get { return created; } }  
  19.     public IDictionary<intstring> CityMap { get { return _cityMap; } }  
  20. }   

Hosting of the Controller

Now we need to host the controller by selfhost or in ASP. Here we use the selfhosting for host the controller that is the simple console application and it can work such as it is hosted in ASP.

  1. HttpSelfHostConfiguration c_config = new HttpSelfHostConfiguration("http://localhost:8080");  
  2. c_config.Routes.MapHttpRoute("_Default""{controller}"new { controller = "_Home" });  
  3. Json_Serializer _serializer = new Json_Serializer();  
  4. _serializer.Converters.Add(new IsoDateTimeConverter());  
  5. c_config.Formatters[0] = new JsonNetFormatter(_serializer);  
  6. server = new HttpSelfHostServer(c_config);  
  7. server.OpenAsync().Wait();   

Access the Controller

The controller is running, now we need to access this controller.For accessing the controller using a HTTP client.

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         HttpSelfHostServer server = null;  
  6.         try  
  7.         {  
  8.             HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:8080");  
  9.             c_config.Routes.MapHttpRoute("_Default""{controller}"new { controller = "_Home" });  
  10.             Json_Serializer _serializer = new Json_Serializer();  
  11.             _serializer.Converters.Add(new IsoDateTimeConverter());  
  12.             c_config.Formatters[0] = new Json_Format(_serializer);  
  13.             server = new HttpSelfHostServer(c_config);  
  14.             server.OpenAsync().Wait();  
  15.             HttpClient c_client = new HttpClient();  
  16.             client.GetAsync("http://localhost:8080").ContinueWith(  
  17.                 (requestTask) =>  
  18.                 {  
  19.                     HttpResponseMessage _response = requestTask.Result;  
  20.                     _response.EnsureSuccessStatusCode();  
  21.                     _response.Content.ReadAsStringAsync().ContinueWith(  
  22.                         (readTask) =>  
  23.                         {  
  24.                             Console.WriteLine(readTask.Result);  
  25.                         });  
  26.                 });  
  27.             Console.WriteLine("press enter for exit");  
  28.             Console.ReadLine();  
  29.         }  
  30.         finally  
  31.         {  
  32.             if (server != null)  
  33.             {  
  34.                server.CloseAsync().Wait();  
  35.             }  
  36.         }  
  37.     }  
  38. }