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.
- public class Json_Format : MediaTypeFormatter
- {
- private Json_Serializer _json_Serializer;
- public Json_Format (Json_Serializer json_Serializer)
- {
- _json_Serializer = json_Serializer ?? new Json_Serializer();
- SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
- encoding = new UTF8encoding(false, true);
- }
- protected override bool Can_ReadType(Type _type)
- {
- if (type == typeof(IKeyValueModel))
- {
- return false;
- }
- return true;
- }
- protected override bool Can_WriteType(Type _type)
- {
- return true;
- }
- protected override Task<object> OnReadFromStream(Type _type, Stream _stream, HttpContentHeaders content_Headers, FormatterContext formatter_Context)
- {
- Json_Serializer s_serializer = Json_Serializer.Create(_json_Serializer);
- return Task.Factory.StartNew(() =>
- {
- using (StreamReader stream_Read = new StreamReader(_stream, encoding))
- {
- using (JsonTextReader json_TextRead = new JsonTextReader(stream_Read))
- {
- return s_serializer.Deserialize(json_TextRead, _type);
- }
- }
- });
- }
- protected override Task OnWriteToStream(Type _type, object _value, Stream _stream, HttpContentHeaders content_Headers, FormatterContext formatter_Context, TransportContext transport_Context)
- {
- Json_Serializer s_serializer = Json_Serializer.Create(_json_Serializer);
- return Task.Factory.StartNew(() =>
- {
- using (StreamWriter stream_Write = new Stream_Write(_stream, encoding))
- {
- using (JsonTextWriter json_TextWrite = new JsonTextWriter(stream_Writer))
- {
- s_serializer.Serialize(jsonTextWriter, _value);
- }
- }
- });
- }
- }
- }
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.
- public class Home_Control : ApiController
- {
- public HomeInfo Get()
- {
- return new HomeInfo();
- }
- }
- public class Home_Info
- {
- private readonly DateTime created = DateTim._UtcNow;
- private readonly Dictionary<int, string> _cityMap = new Dictionary<int, string>
- {
- { 1, "Delhi"},
- { 2, "Nodia" },
- { 3, "Agra" },
- { 4, "Lucknow" },
- };
- public DateTime Created { get { return created; } }
- public IDictionary<int, string> CityMap { get { return _cityMap; } }
- }
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.
- HttpSelfHostConfiguration c_config = new HttpSelfHostConfiguration("http://localhost:8080");
- c_config.Routes.MapHttpRoute("_Default", "{controller}", new { controller = "_Home" });
- Json_Serializer _serializer = new Json_Serializer();
- _serializer.Converters.Add(new IsoDateTimeConverter());
- c_config.Formatters[0] = new JsonNetFormatter(_serializer);
- server = new HttpSelfHostServer(c_config);
- 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.
- class Program
- {
- static void Main(string[] args)
- {
- HttpSelfHostServer server = null;
- try
- {
- HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:8080");
- c_config.Routes.MapHttpRoute("_Default", "{controller}", new { controller = "_Home" });
- Json_Serializer _serializer = new Json_Serializer();
- _serializer.Converters.Add(new IsoDateTimeConverter());
- c_config.Formatters[0] = new Json_Format(_serializer);
- server = new HttpSelfHostServer(c_config);
- server.OpenAsync().Wait();
- HttpClient c_client = new HttpClient();
- client.GetAsync("http://localhost:8080").ContinueWith(
- (requestTask) =>
- {
- HttpResponseMessage _response = requestTask.Result;
- _response.EnsureSuccessStatusCode();
- _response.Content.ReadAsStringAsync().ContinueWith(
- (readTask) =>
- {
- Console.WriteLine(readTask.Result);
- });
- });
- Console.WriteLine("press enter for exit");
- Console.ReadLine();
- }
- finally
- {
- if (server != null)
- {
- server.CloseAsync().Wait();
- }
- }
- }
- }