Cosmos / Document Db client ignores JsonConverter for enums Cosmos / Document Db client ignores JsonConverter for enums json json

Cosmos / Document Db client ignores JsonConverter for enums


I found a workaround that solved my problem:

  • Serialize the object that is supposed to be saved into a json string...
  • ...then deserialize it into a generic JObject...
  • ...and then save that.

Code looks like this:

DocumentClient = new DocumentClient(new Uri(dbServiceEndpoint), dbAuthKey);...var jsonString = JsonConvert.SerializeObject(tick);var jObject = JsonConvert.DeserializeObject(jsonString);var response = DocumentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), jObject);response.Wait();

The enums are transformed into plain strings by this approach. Not very nice, but after all the frustration I'm content with this solution. And at least I didn't need to change any other place.


You should use Azure Functions Cosmos DB output binding to save your document. The following example works as you expect (saves enum value as string).

Code run.csx:

#r "Newtonsoft.Json"using System.Net;using Newtonsoft.Json;using Newtonsoft.Json.Converters;public class Doc{    public string id { get; set; }    [JsonConverter(typeof(StringEnumConverter))]    public OrderActionEnum Action { get; set; }}public enum OrderActionEnum { NEW, CHANGE }public static HttpResponseMessage Run(HttpRequestMessage req, out Doc outputDocument){    outputDocument = new Doc { id = "111", Action = OrderActionEnum.CHANGE };    return req.CreateResponse(HttpStatusCode.OK);}

Bindings function.json:

{  "bindings": [    {      "authLevel": "function",      "name": "req",      "type": "httpTrigger",      "direction": "in"    },    {      "name": "$return",      "type": "http",      "direction": "out"    },    {      "type": "documentDB",      "name": "outputDocument",      "databaseName": "testdb",      "collectionName": "test",      "createIfNotExists": false,      "connection": "my_DOCUMENTDB",      "direction": "out"    }  ],  "disabled": false}

Produced document:

{  "id": "111",  "Action": "CHANGE"}