Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created April 20, 2012 18:47
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save jchadwick/2430984 to your computer and use it in GitHub Desktop.
Save jchadwick/2430984 to your computer and use it in GitHub Desktop.
MSMQ Message JSON Formatter
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;
}
}
@morganski
Copy link

Great, worked a treat. Thanks for sharing!

@Anders2020
Copy link

Just wanted to ask what wrong with the Binaryformatter?
It's not like you are going to use the streamed data outside of MSMQ?

@viridissoftware
Copy link

Thanks Jess - I needed a JSON formatter for testing MSMQ Inspector. Works a treat :-)

@jhlee8804
Copy link

Thanks!

@gumberss
Copy link

Thanks, That's working!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment