Line data Source code
1 : #region Copyright
2 : // // -----------------------------------------------------------------------
3 : // // <copyright company="Chinchilla Software Limited">
4 : // // Copyright Chinchilla Software Limited. All rights reserved.
5 : // // </copyright>
6 : // // -----------------------------------------------------------------------
7 : #endregion
8 :
9 : using System;
10 : using System.Text;
11 : using Newtonsoft.Json;
12 :
13 : namespace Cqrs.EventStore.Bus
14 : {
15 : /// <summary>
16 : /// Converts a stream of JSON text using deserialisation.
17 : /// </summary>
18 : public class EventConverter
19 1 : {
20 : /// <summary>
21 : /// Assumes the provided <paramref name="eventData"/> is a strean of JSON text and
22 : /// deserialises the provided <paramref name="eventData"/> into an object of type <paramref name="typeName"/> then casts to <typeparamref name="TEvent"/>.
23 : /// </summary>
24 : /// <typeparam name="TEvent">The <see cref="Type"/> of the event to convert to.</typeparam>
25 : /// <param name="eventData">A strean of JSON text</param>
26 : /// <param name="typeName">The name of the <see cref="Type"/> to deserialise the provided <paramref name="eventData"/> to.</param>
27 1 : public static TEvent GetEventFromData<TEvent>(byte[] eventData, string typeName)
28 : {
29 : var eventType = Type.GetType(typeName);
30 :
31 : if (eventType == null)
32 : {
33 : return default(TEvent);
34 : }
35 :
36 : string eventjson = Encoding.UTF8.GetString(eventData);
37 : object eventObject = JsonConvert.DeserializeObject(eventjson, eventType);
38 : return (TEvent)eventObject;
39 : }
40 : }
41 : }
|