JSON Serializer

Component: Json Serializer
NuGet Package NServiceBus (6.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 endpointConfiguration = new EndpointConfiguration("Samples.Serialization.Json");
endpointConfiguration.UseSerialization<JsonSerializer>();
// register the mutator so the the message on the wire is written
endpointConfiguration.RegisterMessageMutator(new MessageBodyWriter());

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 Task MutateIncoming(MutateIncomingTransportMessageContext context)
    {
        var bodyAsString = Encoding.UTF8
            .GetString(context.Body);
        log.Info("Serialized Message Body:");
        log.Info(bodyAsString);
        return Task.CompletedTask;
    }
}

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
        },
    }
};
await endpointInstance.SendLocal(message)
    .ConfigureAwait(false);

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