Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Defines a Json <see cref="MediaTypeFormatter"/> using Json.NET serialization/deserialization.
- /// </summary>
- public class JsonNetMediaTypeFormatter : JsonMediaTypeFormatter
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="JsonNetMediaTypeFormatter"/> class.
- /// </summary>
- public JsonNetMediaTypeFormatter()
- {
- SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" });
- SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json") { CharSet = "utf-8" });
- SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
- }
- /// <summary>
- /// Called when [read from stream].
- /// </summary>
- /// <param name="type">The type of object to deserialize.</param>
- /// <param name="stream">The stream.</param>
- /// <param name="httpContentHeaders">The HTTP content headers.</param>
- /// <returns>The de-serialized object.</returns>
- /// <remarks></remarks>
- protected override Object OnReadFromStream(Type type, Stream stream, HttpContentHeaders httpContentHeaders)
- {
- if (type == null)
- {
- throw new ArgumentNullException("type");
- }
- if (stream == null)
- {
- throw new ArgumentNullException("stream");
- }
- return httpContentHeaders.ContentType.MediaType.Equals("application/bson", StringComparison.InvariantCultureIgnoreCase)
- ? stream.ReadAsBson(type)
- : stream.ReadAsJson(type);
- }
- /// <summary>
- /// Called to write an object to the <paramref name="stream"/>.
- /// </summary>
- /// <param name="type">The type of object to write.</param>
- /// <param name="value">The object instance to write.</param>
- /// <param name="stream">The <see cref="T:System.IO.Stream"/> to which to write.</param>
- /// <param name="httpContentHeaders">The HTTP content headers.</param>
- /// <param name="context">The <see cref="T:System.Net.TransportContext"/>.</param>
- /// <remarks></remarks>
- protected override void OnWriteToStream(Type type, Object value, Stream stream, HttpContentHeaders httpContentHeaders, TransportContext context)
- {
- if (type == null)
- {
- throw new ArgumentNullException("type");
- }
- if (stream == null)
- {
- throw new ArgumentNullException("stream");
- }
- if (httpContentHeaders.ContentType.MediaType.Equals("application/bson", StringComparison.InvariantCultureIgnoreCase))
- {
- stream.WriteAsBson(value);
- }
- else
- {
- stream.WriteAsJson(value);
- }
- }
- }
- // ------------------------------------------------------------------------------------------------------
- /// <summary>
- /// Defines extension methods to support Json.NET serialization and deserialization.
- /// </summary>
- public static class JsonNetExtensions
- {
- /// <summary>
- /// Deserializes the JSON-serialized stream and casts it to the object type specified.
- /// </summary>
- /// <typeparam name="T">The type of object to deserialize.</typeparam>
- /// <param name="stream">The stream.</param>
- /// <returns>The deserialized object as type <typeparamref name="T"/></returns>
- public static T ReadAsJson<T>(this Stream stream) where T : class
- {
- return ReadAsJson(stream, typeof(T)) as T;
- }
- /// <summary>
- /// Deserializes the BSON-serialized stream and casts it to the object type specified.
- /// </summary>
- /// <typeparam name="T">The type of object to deserialize.</typeparam>
- /// <param name="stream">The stream.</param>
- /// <returns>The deserialized object as type <typeparamref name="T"/></returns>
- public static T ReadAsBson<T>(this Stream stream) where T : class
- {
- return ReadAsBson(stream, typeof(T)) as T;
- }
- /// <summary>
- /// Reads the JSON-serialized stream and deserializes it into a CLR object.
- /// </summary>
- /// <param name="stream">The stream to deserialize.</param>
- /// <param name="instanceType">Type of the instance.</param>
- /// <returns>The deserialized object.</returns>
- /// <remarks></remarks>
- public static Object ReadAsJson(this Stream stream, Type instanceType)
- {
- if (stream == null)
- {
- return null;
- }
- using (var jsonTextReader = new JsonTextReader(new StreamReader(stream)))
- {
- return Deserialize(jsonTextReader, instanceType);
- }
- }
- /// <summary>
- /// Reads the BSON-serialized stream and deserializes it into a CLR object.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="instanceType">Type of the instance.</param>
- /// <returns>The deserialized object.</returns>
- public static Object ReadAsBson(this Stream stream, Type instanceType)
- {
- if (stream == null)
- {
- return null;
- }
- using (var bsonReader = new BsonReader(stream))
- {
- bsonReader.DateTimeKindHandling = DateTimeKind.Utc;
- return Deserialize(bsonReader, instanceType);
- }
- }
- /// <summary>
- /// Serializes the object into JSON and writes the data into the specified stream.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="instance">The object instance to serialize.</param>
- public static void WriteAsJson(this Stream stream, Object instance)
- {
- if (instance == null)
- {
- return;
- }
- using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(stream)) { CloseOutput = false })
- {
- Serialize(jsonTextWriter, instance);
- }
- }
- /// <summary>
- /// Serializes the object instance into BSON and writes the data into the specified stream.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="instance">The object instance to serialize.</param>
- public static void WriteAsBson(this Stream stream, Object instance)
- {
- if (instance == null)
- {
- return;
- }
- using (var bsonWriter = new BsonWriter(stream) { CloseOutput = false, DateTimeKindHandling = DateTimeKind.Utc })
- {
- Serialize(bsonWriter, instance);
- }
- }
- private static JsonSerializer GetJsonSerializer()
- {
- return new JsonSerializer
- {
- MissingMemberHandling = MissingMemberHandling.Ignore,
- NullValueHandling = NullValueHandling.Ignore,
- ObjectCreationHandling = ObjectCreationHandling.Replace,
- PreserveReferencesHandling = PreserveReferencesHandling.Objects,
- ReferenceLoopHandling = ReferenceLoopHandling.Ignore
- };
- }
- private static JsonSerializer GetBsonSerializer()
- {
- return new JsonSerializer
- {
- MissingMemberHandling = MissingMemberHandling.Ignore,
- NullValueHandling = NullValueHandling.Ignore,
- ObjectCreationHandling = ObjectCreationHandling.Replace,
- PreserveReferencesHandling = PreserveReferencesHandling.Objects,
- ReferenceLoopHandling = ReferenceLoopHandling.Ignore
- };
- }
- private static Object Deserialize(JsonReader jsonReader, Type instanceType)
- {
- try
- {
- using (jsonReader)
- {
- var jsonSerializer = jsonReader is BsonReader
- ? GetBsonSerializer()
- : GetJsonSerializer();
- return jsonSerializer.Deserialize(jsonReader, instanceType);
- }
- }
- catch (JsonReaderException)
- {
- // TODO: (DG) Internal logging?...
- jsonReader.Close();
- throw;
- }
- catch (JsonSerializationException)
- {
- // TODO: (DG) Internal logging?...
- jsonReader.Close();
- throw;
- }
- }
- private static void Serialize(JsonWriter jsonWriter, Object instance)
- {
- try
- {
- var jsonSerializer = jsonWriter is BsonWriter
- ? GetBsonSerializer()
- : GetJsonSerializer();
- jsonSerializer.Serialize(jsonWriter, instance);
- jsonWriter.Flush();
- }
- catch (JsonWriterException)
- {
- // TODO: (DG) Internal logging?...
- jsonWriter.Close();
- throw;
- }
- catch (JsonSerializationException)
- {
- // TODO: (DG) Internal logging?...
- jsonWriter.Close();
- throw;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement