﻿# Newtonsoft JSON Serializer sample

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



This sample uses the Newtonsoft serializer [NServiceBus.Newtonsoft.Json](https://github.com/Particular/NServiceBus.Newtonsoft.Json) to provide full access to the [Newtonsoft Json.net](https://www.newtonsoft.com/json) API.

## Configuring to use NServiceBus.Newtonsoft.Json

<!-- snippet: config -->

```cs
var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.ExternalJson");

var settings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};
var serialization = endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
serialization.Settings(settings);
```

<!-- endsnippet -->

## Diagnostic mutator

A helper that will log the contents of any incoming message:

<!-- 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 -->

Register 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 the message

<!-- snippet: message -->

```cs
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 messageSession.SendLocal(message);

Console.WriteLine("Order Sent");
```

<!-- endsnippet -->

## Output

```json
{
  "OrderId": 9,
  "Date": "2015-09-15T10:23:44.9367871+10:00",
  "CustomerId": 12,
  "OrderItems": [
    {
      "ItemId": 6,
      "Quantity": 2
    },
    {
      "ItemId": 5,
      "Quantity": 4
    }
  ]
}
```
