NServiceBus.Persistence.Sql icon indicating copy to clipboard operation
NServiceBus.Persistence.Sql copied to clipboard

Replacing Newtonsoft with System.Text.Json

Open rogierv opened this issue 2 years ago • 5 comments

Describe the feature.

Are there plans to replace Newtonsoft with System.Text.Json in NServiceBus.Persistence.Sql? Currently, we are implementing NServiceBus 8.1, in which we can use SystemJsonSerializer. This allows us to use the handy JsonDerivedTypes attribute on base classes. It would be great to use them in Sagas as well.

Additional Context

No response

rogierv avatar Aug 07 '23 13:08 rogierv

Hi @rogierv,

Unfortunately it will not be straightforward to replace Newtonsoft with System.Text.Json because users will have stored sagas encoded with Newtonsoft that must still be readable even if new sagas are encoded with System.Text.Json. (Though the fact that SQL Persistence stores the version along with each saga will help.)

But if all you're after is serialization of polymorphic types in your saga data, Newtonsoft can already handle that.

Add this to your endpoint configuration:

var persistence = endpointConfiguration.UsePersistence<SqlPersistence>();
var sagaSettings = persistence.SagaSettings();
sagaSettings.JsonSettings(new JsonSerializerSettings
{
   TypeNameHandling = TypeNameHandling.Auto 
});

Then if the actual type of the object differs from the declared type, Newtonsoft will output a "$type":"YourTypeName" in the object that it will use on deserialization.

Here is the Newtonsoft documentation for the TypeNameHandling options.

DavidBoike avatar Aug 10 '23 13:08 DavidBoike

Thank you, @DavidBoike, for your explanation. It's good to know that there is an option to configure serialization at the endpoint.

rogierv avatar Aug 15 '23 07:08 rogierv

any progress on this?

users will have stored sagas encoded with Newtonsoft that must still be readable even if new sagas are encoded with System.Text.Json

an interim version that reads in Newtonsoft + System.Text.Json and writes in System.Text.Json should make this possible

SimonCropp avatar Mar 08 '24 01:03 SimonCropp