3

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.

Raghav
  • 127
  • 2
  • 7
  • I've just tested your code and it seems to be working fine with both Replace and Upsert method. `EnumProertyName` is always a string. – Nick Chapsas Aug 05 '18 at 00:57
  • @Raghav Please add your client code and error you met. – Jay Gong Aug 06 '18 at 06:02
  • @JayGong I haven't got any error. It simply doesn't serialize to the value I set and always serializes tot he default value. I got rid of the error by not inheriting from Document ans creating a simple POCO that has the id property and everything worked as expected. – Raghav Aug 07 '18 at 02:47

2 Answers2

6

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);
Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53
0

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.

Olha Shumeliuk
  • 720
  • 7
  • 14