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);
- }
- }
- });
- }
- }
- }

Join the conversation! Your thoughts help the community grow.