Search code examples
c#json.netazure-cosmosdbsystem.text.json

Why is Azure CosmosDB saving dictionary Object values as "ValueKind": number?


I am using C# .Net 8.0, the Azure Cosmos DB SDK 3.40.0 (NoSQL). I have a record defined as follows (all NON-relevant fields and code have been removed), i.e.:

  public record test_rec {
      
      private System.Collections.Generic.Dictionary<String, Object> m_custom;
      
      public System.Collections.Generic.Dictionary<String, Object> custom
      {

         get
         {
            return m_custom;
         }

         set
         {
            m_custom = value;
         }

      }
      
      // Constructor ...

      public test_rec()
      {

         init_members();

      }

      private void init_members()
      {

         m_custom = null;

      }
      
  }

The "custom" property is used to store keys and values, for example:

test_rec rec;
  
rec = new test_rec();

rec.custom = new System.Collections.Generic.Dictionary<String,Object>();

rec.custom.Add( "key1", null );
rec.custom.Add( "key2", "string" );
rec.custom.Add( "key3", 100 );

I can create a record (save it to the DB) using the Cosmos DB SDK without any issue. However, when I examine the record properties (via the Azure Portal), I see the following JSON:

     "custom": {
        "key1": null,
        "key2": {
            "ValueKind": 3
        },
        "key3": {
            "ValueKind": 4
        }
    },

I was expecting the following:

   "custom": {
      "key1": null,
      "key2": "string",
      "key3": 100
   }

Can someone please elaborate on this behavior or provide instructions on how to retain the values in the dictionary or provide a workaround?

Thanks in advance.


Solution

  • One workaround I found (from the SO question 76693447), is to use a custom serializer that leverages System.Text.Json. The relevant code can be found at:

    https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson

    However, if anyone else has some ideas or solutions, please feel free to post.

    Microsoft - is this the only solution at this time?