Azure Cosmos DB SDK 3+ for SQL API replaced Azure DocumentDB SDK a couple of years back. DocumentDB used Newtonsoft Json.NET for its serialization. However, with the growth of .NET Core and the introduction of shiny new System.Text.Json, the team wanted to reduce exposure to Newtonsoft. So the idea was in future, with CosmosDB SDK 4, System.Text.Json would replace Json.NET.
The unfortunate side-effect of this was that we do not have an easy way to supply custom JSON serializer settings. The SDK allows us to update a limited set of JSON settings such as
PropertyNamePolicy through CosmosSerializationOptions. However, in the real world scenario, this is not always enough.
The CosmosSerializer class from the SDK is
abstractand all its implementation, such as
sealed. I also raised an issue with the developer team to fix this limitation.
CUSTOM JSON Serializer for Cosmos
Fix for this issue is easy, albeit ugly. We can create our own
CosmosJsonDotNetSerializer inspired from Cosmos DB SDK as below:
As you can see in the above code
JsonSerializerSettings as a parameter in its Constructor.
This would allow us to create
CosmosJsonDotNetSerializer and pass our own
JsonSerializerSettings as shown in the code snippet below:
BUT WAIT… THERE IS MORE
I raised a question to the Cosmos DB team sometime back if there is a way to use replace Json.NET with System.Text.Json. Mark Brown, from the Cosmos DB team, responded that we can easily do that by extending
CosmosSerializer like we did above.
Here is the System.Text.Json implementation of CosmosSerializer. The implementation is inspired by Azure Cosmos Samples.
We can now use the serializer to create
CosmosClient as below
This post explains a workaround to create custom serializer settings using Json.NET and System.Text.Json when working with Cosmos DB. Hopefully, this workaround is short-lived and with the release of v4 we get this option out of the box.