Created
April 20, 2012 18:47
-
-
Save jchadwick/2430984 to your computer and use it in GitHub Desktop.
MSMQ Message JSON Formatter
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.IO; | |
using System.Messaging; | |
using System.Text; | |
using Newtonsoft.Json; | |
public class JsonMessageFormatter : IMessageFormatter | |
{ | |
private static readonly JsonSerializerSettings DefaultSerializerSettings = | |
new JsonSerializerSettings { | |
TypeNameHandling = TypeNameHandling.Objects | |
}; | |
private readonly JsonSerializerSettings _serializerSettings; | |
public Encoding Encoding { get; set; } | |
public JsonMessageFormatter(Encoding encoding = null) | |
: this(encoding, null) | |
{ | |
} | |
internal JsonMessageFormatter(Encoding encoding, JsonSerializerSettings serializerSettings = null) | |
{ | |
Encoding = encoding ?? Encoding.UTF8; | |
_serializerSettings = serializerSettings ?? DefaultSerializerSettings; | |
} | |
public bool CanRead(Message message) | |
{ | |
if (message == null) | |
throw new ArgumentNullException("message"); | |
var stream = message.BodyStream; | |
return stream != null | |
&& stream.CanRead | |
&& stream.Length > 0; | |
} | |
public object Clone() | |
{ | |
return new JsonMessageFormatter(Encoding, _serializerSettings); | |
} | |
public object Read(Message message) | |
{ | |
if (message == null) | |
throw new ArgumentNullException("message"); | |
if(CanRead(message) == false) | |
return null; | |
using (var reader = new StreamReader(message.BodyStream, Encoding)) | |
{ | |
var json = reader.ReadToEnd(); | |
return JsonConvert.DeserializeObject(json, _serializerSettings); | |
} | |
} | |
public void Write(Message message, object obj) | |
{ | |
if (message == null) | |
throw new ArgumentNullException("message"); | |
if (obj == null) | |
throw new ArgumentNullException("obj"); | |
string json = JsonConvert.SerializeObject(obj, Formatting.None, _serializerSettings); | |
message.BodyStream = new MemoryStream(Encoding.GetBytes(json)); | |
//Need to reset the body type, in case the same message | |
//is reused by some other formatter. | |
message.BodyType = 0; | |
} | |
} |
Just wanted to ask what wrong with the Binaryformatter?
It's not like you are going to use the streamed data outside of MSMQ?
Thanks Jess - I needed a JSON formatter for testing MSMQ Inspector. Works a treat :-)
Thanks!
Thanks, That's working!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great, worked a treat. Thanks for sharing!