azure-cosmos-dotnet-v3: Enum cannot be serialized as string in CosmosDb

I have an object that I wan’t to save as a document in a CosmosDb container. This object contains some Enum properties. I did not find a way to serialize these properties as string in CosmosDb. They are serialized as their int value. I looked at CosmosSerializerOptions but I did not see a way to configure that.

Moreover, on my object the id of my document is also an ennum property so when I try to create the document I have this error:

Microsoft.Azure.Cosmos.CosmosException: 'Response status code does not indicate success: 400 Substatus: 0 Reason: (Message: {"Errors":["The input name '0' is invalid. Ensure to provide a unique non-empty string less than '1024' characters."]}

Am I missing something or is handling enum not implemented yet in the sdk ? Is there any workaround known ? Maybe using NewtonSoft serializer as the serializer ?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 2
  • Comments: 16 (5 by maintainers)

Most upvoted comments

I succeeded to make it work. Thank you so much for your help @j82w ! What is weird is that I did the same thing that I was doing before but from another laptop. I wonder what was causing the issue … but nevermind it works now, I will check my work laptop tomorrow. I close the issue but I think it would make sense to add a setting for enum in the CosmosSerializerOptions in a future version of the sdk. Thanks again 👍.

Is there a solution for this? why is closed? I continue having issues with System.Text.Json.Serialization as it’s the recommendation since net core 3.1 and we are on days for net7 releases.

this works:

[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public Status Status { get; set; }

but this doesn’t work and should:

[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
public Status Status { get; set; }

using Microsoft.Azure.Cosmos 3.31.0 net 6.0.402

By any chance do you have using system.text.json in your project? Is it a .net core 3.0 app? My only thought is that the [JsonConverter(typeof(StringEnumConverter))] is from the wrong package and that’s why it’s getting ignored.

I did some testing and putting [JsonConverter(typeof(StringEnumConverter))] on the enum class or the property correctly serialized it to a string instead of a number.

 [JsonConverter(typeof(StringEnumConverter))]
        public enum Priority
        {
            None,
            Low,
            Medium,
            High
        }