﻿# Newtonsoft BSON Serializer

<!-- Version variant: newtonsoft_4; default: [/samples/serializers/newtonsoft-bson/index.md](/samples/serializers/newtonsoft-bson/index.md) -->


This sample uses the Newtonsoft serializer [NServiceBus.Newtonsoft.Json](https://github.com/Particular/NServiceBus.Newtonsoft.Json) and configures it to use [BSON](http://bsonspec.org/).

## Configuration

<!-- snippet: config -->

```cs
var serialization = endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
serialization.ContentTypeKey("application/bson");
serialization.ReaderCreator(stream => new BsonDataReader(stream));
serialization.WriterCreator(stream => new BsonDataWriter(stream));
```

<!-- endsnippet -->

## Diagnostic mutator

This helper will write out the contents of any incoming message so that the serialization can be observed.

<!-- snippet: mutator -->

```cs
public class MessageBodyWriter(ILogger<MessageBodyWriter> logger) :
    IMutateIncomingTransportMessages
{
    public Task MutateIncoming(MutateIncomingTransportMessageContext context)
    {
        var bodyAsString = Encoding.UTF8
            .GetString(context.Body.ToArray());

        logger.LogInformation   ("Serialized Message Body:");
        logger.LogInformation(bodyAsString);

        return Task.CompletedTask;
    }
}
```

<!-- endsnippet -->

This registers the mutator:

<!-- snippet: registermutator -->

```cs
builder.Services.AddSingleton<MessageBodyWriter>();

// Then later get it from the service provider when needed
var serviceProvider = builder.Services.BuildServiceProvider();
var messageBodyWriter = serviceProvider.GetRequiredService<MessageBodyWriter>();
endpointConfiguration.RegisterMessageMutator(messageBodyWriter);
```

<!-- endsnippet -->

## Sending a message

<!-- snippet: message -->

```cs
var message = new CreateOrder
{
    OrderId = 9,
    Date = DateTime.Now,
    CustomerId = 12,
    OrderItems =
    [
        new OrderItem
        {
            ItemId = 6,
            Quantity = 2
        },
        new OrderItem
        {
            ItemId = 5,
            Quantity = 4
        }

    ]
};
await messageSession.SendLocal(message);
```

<!-- endsnippet -->
