'How do I configure Cosmos DB .NET 3.0 SDK to serialize with camel case?

My .NET POCOs are in ProperCase. My json is in camelCase. How can I configure version 3.0 of the .NET SDK to convert when serializing/deserializing to/from Cosmos DB?

I know I can add the attribute [JsonProperty(PropertyName = "myProperty")] to each property but how can I tell the SDK to do this for all properties by default?

I'm trying to get away from adding an attribute for this to every property.



Solution 1:[1]

var client = new CosmosClientBuilder("URI", "Key")
        .WithSerializerOptions(new CosmosSerializationOptions {  PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase })
        .Build();

Solution 2:[2]

It's a bit quick and dirty but to keep you moving until Microsoft exposes the serializer settings of the default serializer, you could copy the existing CosmosJsonSerializer and pass in the JsonSerializerSettings to the constructor.

I've created a gist you can take here:

Newtonsoft JSON.NET Serializer for Cosmos .net SDK v3

Solution 3:[3]

You can configure your own JSON serializer class using the JSON.Net settings you need.

var cosmos = new CosmosClientBuilder("http://cosmosdb", "key")
                .UseCustomJsonSerializer(new CustomJsonSerializer())
                .Build();

The abstract class definition for CosmosJsonSerializer is a simple pair of to/from stream to T methods.

Solution 4:[4]

It looks like the serializer settings are now exposed, so you can do:

        var client = new CosmosClient(uri, key, new CosmosClientOptions()
        {
            SerializerOptions = new CosmosSerializationOptions()
            {
                PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase,
            }
        });

I've tested this using Microsoft.Azure.Cosmos 3.26.1, and with this, the WHERE clause in my LINQ queries properly will map "PropertyId" in my POCO to "propertyId" in my document.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj Rao
Solution 2 Rich S
Solution 3 Mani Gandham
Solution 4 BenjiFB