JSON Serializer

Component: Json Serializer
NuGet Package NServiceBus (5.x)
In Versions 7 and above of NServiceBus, the JsonSerializer has been removed. Use the external Json.NET Serializer instead. See also Compatibility between the core and external Json.NET serializer.

This samples uses the JSON serializer in the core.

Configuring to use JSON

var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.Serialization.Json");
busConfiguration.UseSerialization<JsonSerializer>();
// register the mutator so the the message on the wire is written
busConfiguration.RegisterComponents(components =>
{
    components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall);
});

Diagnostic Mutator

A helper that will Write out the contents of any incoming message.

public class MessageBodyWriter :
    IMutateIncomingTransportMessages
{
    static ILog log = LogManager.GetLogger<MessageBodyWriter>();

    public void MutateIncoming(TransportMessage transportMessage)
    {
        var bodyAsString = Encoding.UTF8
            .GetString(transportMessage.Body);
        log.Info("Serialized Message Body:");
        log.Info(bodyAsString);
    }
}

The message send

var message = new CreateOrder
{
    OrderId = 9,
    Date = DateTime.Now,
    CustomerId = 12,
    OrderItems = new List<OrderItem>
    {
        new OrderItem
        {
            ItemId = 6,
            Quantity = 2
        },
        new OrderItem
        {
            ItemId = 5,
            Quantity = 4
        },
    }
};
bus.SendLocal(message);

The Output

{
	"OrderId":9,
	"Date":"2015-09-15T13:42:00.2776276+10:00",
	"CustomerId":12,
	"OrderItems":
	[
		{
			"ItemId":6,
			"Quantity":2
		},
		{
			"ItemId":5,
			"Quantity":4
		}
	]
}

Related Articles


Last modified