Reputation: 1172
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();
}
Upvotes: 1
Views: 1430
Reputation: 15603
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
Upvotes: 2