Reputation: 127
I am using Json.Net to decorate my document properties.
public class MyDocumentType : Document
{
[JsonProperty]
[JsonConverter(typeof(StringEnumConverter))]
public MyEnumType EnumProertyName{ get; set; }
[JsonProperty]
public uint MyIntPrperty{ get; set; }
}
When I update the document in cosmos db, it is not getting updated to string value. It is always defaulting to the default enum value. How do I make it serialize and deserialize to string value. I don't want to use numbers as if I add a new enum value then things will break.
Upvotes: 4
Views: 5545
Reputation: 4078
With Cosmos DB SDK 3+, you cannot pass JsonSerializerSettings
directly.
You would need to extend CosmosSerializer
. You can get the an example of CosmosSerializer
implementation from CosmosJsonDotNetSerializer in Cosmos DB SDK.
Unfortunately, this class is internal
sealed
so you may have copy verbatim in your code. I have also raised a GitHub issue asking the Cosmos team to address this issue here.
Once, you have an implementation for CosmosSerializer available in your code, you can pass JsonSerializerSettings
as below:
// Create CosmosClientOptions
var cosmosClientOptions = new CosmosClientOptions
{
Serializer =
new CosmosJsonDotNetSerializer(
new JsonSerializerSettings() {
// Your JSON Serializer settings
})
};
var cosmosClient = new CosmosClient(connectionString, cosmosClientOptions);
Upvotes: 7
Reputation: 740
When constructing DocumentClient
object you are allowed to pass JsonSerializerSettings
object. In that object you need to add handling of string values like this:
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
DateFormatString = "o",
DateFormatHandling = DateFormatHandling.IsoDateFormat,
Converters = new List<JsonConverter>
{
new Newtonsoft.Json.Converters.StringEnumConverter()
{
AllowIntegerValues = true
}
},
};
StringEnumConverter
- this should serialize/deserialize your enums to string, while also allow to parse back from int.
Upvotes: 0