1

How can I tell Cosmos SDK to write documents with camel case without using [JsonPropertyName] in all properties of the model?

For instance in this example of code.

        [FunctionName("CreaUsers")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users")]
                HttpRequest req,
            [CosmosDB(
                databaseName: Database.Name,
                containerName: Database.Container,
                Connection = "CosmosDBConnection")] CosmosClient client,
            ILogger log)
        {

            var container = client.GetDatabase(Database.Name).GetContainer(Database.Container);

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var user = JsonSerializer.Deserialize<User>(requestBody);

            var id = Guid.NewGuid();
            user.Id = id;
            user.UserId = id.ToString();

            var result = await container.CreateItemAsync(user, new PartitionKey(id.ToString()));

            log.LogInformation($"C# HTTP trigger function inserted one row");

            return new NoContentResult();
        }
osotorrio
  • 960
  • 1
  • 11
  • 30

1 Answers1

2

You are using the 4.0.0 extension, which comes with the possibility of customizing the serialization engine completely.

Assuming you have a Functions Startup, you can inject your own custom ICosmosDBSerializerFactory implementation that uses your own custom CosmosSerializer.

For example:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddSingleton<ICosmosDBSerializerFactory, MyCosmosDBSerializerFactory>();
    }
}

public class MyCosmosDBSerializerFactory : ICosmosDBSerializerFactory
{
    public CosmosSerializer CreateSerializer()
    {
        return new MyCustomCosmosSerializer();
    }
}

You could even use System.Text.Json if you wanted, using an implementation like: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson/CosmosSystemTextJsonSerializer.cs

Reference: https://www.youtube.com/watch?v=w002dYaP9mw&t=735s

Matias Quaranta
  • 13,907
  • 1
  • 22
  • 47
  • This doesn't appear to work for me with isolated process functions. I found the issue here: https://github.com/Azure/azure-webjobs-sdk-extensions/issues/743 they claim for it to be resolved in preview2 but It's still not working for me – Street0 Nov 22 '22 at 16:12
  • Isolated Process Functions use a different nuget package, it might be related to that package, I am not aware of which are the differences, my comment is over the base Cosmos DB Extension package – Matias Quaranta Nov 22 '22 at 17:21