Advertisement
Guest User

Json.NET MediaTypeFormatter

a guest
Feb 5th, 2012
1,303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.75 KB | None | 0 0
  1. /// <summary>
  2. /// Defines a Json <see cref="MediaTypeFormatter"/> using Json.NET serialization/deserialization.
  3. /// </summary>
  4. public class JsonNetMediaTypeFormatter : JsonMediaTypeFormatter
  5. {
  6.     /// <summary>
  7.     /// Initializes a new instance of the <see cref="JsonNetMediaTypeFormatter"/> class.
  8.     /// </summary>
  9.     public JsonNetMediaTypeFormatter()
  10.     {
  11.         SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" });
  12.         SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json") { CharSet = "utf-8" });
  13.         SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
  14.     }
  15.  
  16.     /// <summary>
  17.     /// Called when [read from stream].
  18.     /// </summary>
  19.     /// <param name="type">The type of object to deserialize.</param>
  20.     /// <param name="stream">The stream.</param>
  21.     /// <param name="httpContentHeaders">The HTTP content headers.</param>
  22.     /// <returns>The de-serialized object.</returns>
  23.     /// <remarks></remarks>
  24.     protected override Object OnReadFromStream(Type type, Stream stream, HttpContentHeaders httpContentHeaders)
  25.     {
  26.         if (type == null)
  27.         {
  28.             throw new ArgumentNullException("type");
  29.         }
  30.  
  31.         if (stream == null)
  32.         {
  33.             throw new ArgumentNullException("stream");
  34.         }
  35.  
  36.         return httpContentHeaders.ContentType.MediaType.Equals("application/bson", StringComparison.InvariantCultureIgnoreCase)
  37.             ? stream.ReadAsBson(type)
  38.             : stream.ReadAsJson(type);
  39.     }
  40.  
  41.     /// <summary>
  42.     /// Called to write an object to the <paramref name="stream"/>.
  43.     /// </summary>
  44.     /// <param name="type">The type of object to write.</param>
  45.     /// <param name="value">The object instance to write.</param>
  46.     /// <param name="stream">The <see cref="T:System.IO.Stream"/> to which to write.</param>
  47.     /// <param name="httpContentHeaders">The HTTP content headers.</param>
  48.     /// <param name="context">The <see cref="T:System.Net.TransportContext"/>.</param>
  49.     /// <remarks></remarks>
  50.     protected override void OnWriteToStream(Type type, Object value, Stream stream, HttpContentHeaders httpContentHeaders, TransportContext context)
  51.     {
  52.         if (type == null)
  53.         {
  54.             throw new ArgumentNullException("type");
  55.         }
  56.  
  57.         if (stream == null)
  58.         {
  59.             throw new ArgumentNullException("stream");
  60.         }
  61.  
  62.         if (httpContentHeaders.ContentType.MediaType.Equals("application/bson", StringComparison.InvariantCultureIgnoreCase))
  63.         {
  64.             stream.WriteAsBson(value);
  65.         }
  66.         else
  67.         {
  68.             stream.WriteAsJson(value);
  69.         }
  70.     }
  71. }
  72.  
  73. // ------------------------------------------------------------------------------------------------------
  74.  
  75. /// <summary>
  76. /// Defines extension methods to support Json.NET serialization and deserialization.
  77. /// </summary>
  78. public static class JsonNetExtensions
  79. {
  80.     /// <summary>
  81.     /// Deserializes the JSON-serialized stream and casts it to the object type specified.
  82.     /// </summary>
  83.     /// <typeparam name="T">The type of object to deserialize.</typeparam>
  84.     /// <param name="stream">The stream.</param>
  85.     /// <returns>The deserialized object as type <typeparamref name="T"/></returns>
  86.     public static T ReadAsJson<T>(this Stream stream) where T : class
  87.     {
  88.         return ReadAsJson(stream, typeof(T)) as T;
  89.     }
  90.  
  91.     /// <summary>
  92.     /// Deserializes the BSON-serialized stream and casts it to the object type specified.
  93.     /// </summary>
  94.     /// <typeparam name="T">The type of object to deserialize.</typeparam>
  95.     /// <param name="stream">The stream.</param>
  96.     /// <returns>The deserialized object as type <typeparamref name="T"/></returns>
  97.     public static T ReadAsBson<T>(this Stream stream) where T : class
  98.     {
  99.         return ReadAsBson(stream, typeof(T)) as T;
  100.     }
  101.  
  102.     /// <summary>
  103.     /// Reads the JSON-serialized stream and deserializes it into a CLR object.
  104.     /// </summary>
  105.     /// <param name="stream">The stream to deserialize.</param>
  106.     /// <param name="instanceType">Type of the instance.</param>
  107.     /// <returns>The deserialized object.</returns>
  108.     /// <remarks></remarks>
  109.     public static Object ReadAsJson(this Stream stream, Type instanceType)
  110.     {
  111.         if (stream == null)
  112.         {
  113.             return null;
  114.         }
  115.  
  116.         using (var jsonTextReader = new JsonTextReader(new StreamReader(stream)))
  117.         {
  118.             return Deserialize(jsonTextReader, instanceType);
  119.         }
  120.     }
  121.  
  122.     /// <summary>
  123.     /// Reads the BSON-serialized stream and deserializes it into a CLR object.
  124.     /// </summary>
  125.     /// <param name="stream">The stream.</param>
  126.     /// <param name="instanceType">Type of the instance.</param>
  127.     /// <returns>The deserialized object.</returns>
  128.     public static Object ReadAsBson(this Stream stream, Type instanceType)
  129.     {
  130.         if (stream == null)
  131.         {
  132.             return null;
  133.         }
  134.  
  135.         using (var bsonReader = new BsonReader(stream))
  136.         {
  137.             bsonReader.DateTimeKindHandling = DateTimeKind.Utc;
  138.  
  139.             return Deserialize(bsonReader, instanceType);
  140.         }
  141.     }
  142.  
  143.     /// <summary>
  144.     /// Serializes the object into JSON and writes the data into the specified stream.
  145.     /// </summary>
  146.     /// <param name="stream">The stream.</param>
  147.     /// <param name="instance">The object instance to serialize.</param>
  148.     public static void WriteAsJson(this Stream stream, Object instance)
  149.     {
  150.         if (instance == null)
  151.         {
  152.             return;
  153.         }
  154.  
  155.         using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(stream)) { CloseOutput = false })
  156.         {
  157.             Serialize(jsonTextWriter, instance);
  158.         }
  159.     }
  160.  
  161.     /// <summary>
  162.     /// Serializes the object instance into BSON and writes the data into the specified stream.
  163.     /// </summary>
  164.     /// <param name="stream">The stream.</param>
  165.     /// <param name="instance">The object instance to serialize.</param>
  166.     public static void WriteAsBson(this Stream stream, Object instance)
  167.     {
  168.         if (instance == null)
  169.         {
  170.             return;
  171.         }
  172.  
  173.         using (var bsonWriter = new BsonWriter(stream) { CloseOutput = false, DateTimeKindHandling = DateTimeKind.Utc })
  174.         {
  175.             Serialize(bsonWriter, instance);
  176.         }
  177.     }
  178.  
  179.     private static JsonSerializer GetJsonSerializer()
  180.     {
  181.         return new JsonSerializer
  182.             {
  183.                 MissingMemberHandling = MissingMemberHandling.Ignore,
  184.                 NullValueHandling = NullValueHandling.Ignore,
  185.                 ObjectCreationHandling = ObjectCreationHandling.Replace,
  186.                 PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  187.                 ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  188.             };
  189.     }
  190.  
  191.     private static JsonSerializer GetBsonSerializer()
  192.     {
  193.         return new JsonSerializer
  194.         {
  195.             MissingMemberHandling = MissingMemberHandling.Ignore,
  196.             NullValueHandling = NullValueHandling.Ignore,
  197.             ObjectCreationHandling = ObjectCreationHandling.Replace,
  198.             PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  199.             ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  200.         };
  201.     }
  202.  
  203.     private static Object Deserialize(JsonReader jsonReader, Type instanceType)
  204.     {
  205.         try
  206.         {
  207.             using (jsonReader)
  208.             {
  209.                 var jsonSerializer = jsonReader is BsonReader
  210.                     ? GetBsonSerializer()
  211.                     : GetJsonSerializer();
  212.                    
  213.                 return jsonSerializer.Deserialize(jsonReader, instanceType);
  214.             }
  215.         }
  216.         catch (JsonReaderException)
  217.         {
  218.             // TODO: (DG) Internal logging?...
  219.             jsonReader.Close();
  220.             throw;
  221.         }
  222.         catch (JsonSerializationException)
  223.         {
  224.             // TODO: (DG) Internal logging?...
  225.             jsonReader.Close();
  226.             throw;
  227.         }
  228.     }
  229.  
  230.     private static void Serialize(JsonWriter jsonWriter, Object instance)
  231.     {
  232.         try
  233.         {
  234.             var jsonSerializer = jsonWriter is BsonWriter
  235.                     ? GetBsonSerializer()
  236.                     : GetJsonSerializer();
  237.  
  238.             jsonSerializer.Serialize(jsonWriter, instance);
  239.             jsonWriter.Flush();
  240.         }
  241.         catch (JsonWriterException)
  242.         {
  243.             // TODO: (DG) Internal logging?...
  244.             jsonWriter.Close();
  245.             throw;
  246.         }
  247.         catch (JsonSerializationException)
  248.         {
  249.             // TODO: (DG) Internal logging?...
  250.             jsonWriter.Close();
  251.             throw;
  252.         }
  253.     }
  254. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement