繁体   English   中英

从 JSON 反序列化 IndexingPolicy(Azure Cosmos DB)

[英]Deserialize IndexingPolicy(Azure Cosmos DB) from JSON

我正在尝试从 json IndexingPolicy 反序列化以更新 Azure Cosmos DB。 虽然 IndexingPolicy 及其所有内部 class 都是 JsonSerializable 的子类,但它无法反序列化。

索引是 IndexingPolicy 的内部 class 之一,并且缺少空构造函数。 因此,反序列化失败。 但是,我很难相信框架的开发人员没有正确测试它。

我尝试了两种反序列化方法,

    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); 

并且还通过 LoadFrom() 方法,

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

为了安全起见,我也尝试了这个 JSON

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

使用默认 Newtonsoft.Json 设置可以正常工作:

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

请记住,您在示例中使用的索引定义似乎不正确, dataTypekind是数字,似乎必须是实际名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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