JSON Serializer

Component: Json Serializer
NuGet Package NServiceBus (6.x)
In NServiceBus version 7 and above, 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 log 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;
    }
}

Sending the message

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);

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

  • JSON Serializer
    A JSON serializer that uses Json.NET.
  • Serialization
    Information about how messages are serialized and deserialized on a transport.

Last modified