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

4

12

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.

Diggins answered 10/5, 2019 at 20:15 Comment(0)
K
12
var client = new CosmosClientBuilder("URI", "Key")
        .WithSerializerOptions(new CosmosSerializationOptions {  PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase })
        .Build();
Kindig answered 26/8, 2019 at 15:2 Comment(1)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Overzealous
C
6

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.

Caddy answered 16/4, 2022 at 12:39 Comment(0)
R
4

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

Rhododendron answered 16/7, 2019 at 22:25 Comment(0)
U
1

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.

Unrestraint answered 20/5, 2019 at 23:21 Comment(1)
But this is very different from the options in System.Text.Json.SerializationAnthropo

© 2022 - 2024 — McMap. All rights reserved.