[英]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);
請記住,您在示例中使用的索引定義似乎不正確, dataType
和kind
是數字,似乎必須是實際名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.