Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Newtonsoft JSON Serializer sample

NuGet Package: NServiceBus.Newtonsoft.Json (2.x)
Target Version: NServiceBus 7.x

This sample uses the Newtonsoft serializer NServiceBus.Newtonsoft.Json to provide full access to the Newtonsoft Json.net API.

Configuring to use NServiceBus.Newtonsoft.Json

var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.ExternalJson");
var settings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};
var serialization = endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
serialization.Settings(settings);

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

Register the mutator:

endpointConfiguration.RegisterComponents(
    registration: components =>
    {
        components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall);
    });

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

Output

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

Samples

Related Articles

  • Serialization
    .NET messaging systems require serialization and deserialization of objects sent/received over transports. NServiceBus achieves this using serializers.