Last active
November 20, 2016 21:59
-
-
Save ritasker/8c0dce84cfc7bfb0f14494a260a5099a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using RabbitMQ.Client.Events; | |
using RawRabbit.Common; | |
using RawRabbit.Serialization; | |
using ServiceStack; | |
using ServiceStack.Text; | |
namespace ConsoleApplication | |
{ | |
public class ServiceStackSerialiser : IMessageSerializer | |
{ | |
public object Deserialize(BasicDeliverEventArgs args) | |
{ | |
object typeBytes; | |
if (args.BasicProperties.Headers.TryGetValue(PropertyHeaders.MessageType, out typeBytes)) | |
{ | |
var typeName = Encoding.UTF8.GetString(typeBytes as byte[] ?? new byte[0]); | |
var type = Type.GetType(typeName, false); | |
return Deserialize(args.Body, type); | |
} | |
else | |
{ | |
var typeName = args.BasicProperties.Type; | |
var type = Type.GetType(typeName, false); | |
return Deserialize(args.Body, type); | |
} | |
} | |
public object Deserialize(byte[] bytes, Type messageType) | |
{ | |
var json = Encoding.UTF8.GetString(bytes); | |
return JsonSerializer.DeserializeFromString(json, messageType); | |
} | |
public T Deserialize<T>(byte[] bytes) | |
{ | |
return (T)Deserialize(bytes, typeof(T)); | |
} | |
public byte[] Serialize<T>(T obj) | |
{ | |
if (obj == null) | |
return Encoding.UTF8.GetBytes(string.Empty); | |
var json = obj.ToJson(); | |
return Encoding.UTF8.GetBytes(json); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment