简体   繁体   中英

Deserialize IndexingPolicy(Azure Cosmos DB) from JSON

I'm trying to deserialize from a json IndexingPolicy in order to update the Azure Cosmos DB. Although IndexingPolicy and all its inner class are subclasses of JsonSerializable, it fails to be deserialized.

Index is one of the inner class of IndexingPolicy and is lack of empty constructor. Therefore, the deserialization fails. However, I find it hard to believe that the developers of the framework haven't tested it properly.

I have tried two ways to deserialize,

    var jsonString = @"{
      'indexingMode': 'consistent',
      'automatic': true,
      'includedPaths': [
        {
          'path': '/PartitionKey/?',
          'indexes': [
            {
              'kind': 'Range',
              'dataType': 'String',
              'precision': -1
            }
          ]
        }
      ],
      'excludedPaths': [
        {
          'path': '/*'
        }
      ]
    }";
    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        IgnoreNullValues = true,
        IgnoreReadOnlyProperties = true,
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        AllowTrailingCommas = false,
        MaxDepth = 1000,
        PropertyNameCaseInsensitive = true
    };
    IndexingPolicy index = System.Text.Json.JsonSerializer.Deserialize<IndexingPolicy>(jsonString, options); 

And also by LoadFrom() method,

        IndexingPolicy ip = new IndexingPolicy();
        using (var reader = new JsonTextReader(new StringReader(jsonString)))
        {
            ip.LoadFrom(reader);
        } 

To be on the safe side I also tried with this JSON

{
      "indexingMode": 0,
      "automatic": true,
      "includedPaths": [
        {
          "path": "/PartitionKey/?",
          "indexes": [
            {
              "kind": 1,
              "dataType": 1,
              "precision": -1
            }
          ]
        }
      ],
      "excludedPaths": [
        {
          "path": "/*"
        }
      ]
    }

Using the default Newtonsoft.Json settings works without issues:

string serializedPolicy = @"{
  ""indexingMode"": 0,
  ""automatic"": true,
  ""includedPaths"": [
    {
      ""path"": ""/PartitionKey/?"",
      ""indexes"":[{""dataType"":""Number"",""precision"":-1,""kind"":""Hash""}]
    }
  ],
  ""excludedPaths"": [
    {
       ""path"": ""/*""
    }
  ]
}";
IndexingPolicy policy = JsonConvert.DeserializeObject<IndexingPolicy>(serializedPolicy);

Keep in mind that the index definition you are using in your example seems to be incorrect, the dataType and kind are numbers, which seem to have to be the actual names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM