我正在尝试从JSON IndexingPolicy反序列化以更新Azure Cosmos数据库。 尽管IndexingPolicy及其所有内部类都是JsonSerializable的子类,但无法对其进行反序列化。
Index是IndexingPolicy的内部类之一,并且缺少空的构造方法。因此,反序列化失败。但是,我很难相信该框架的开发人员没有对其进行正确的测试。
我尝试了两种反序列化的方法,
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": "/*"
}
]
}
答案 0 :(得分:0)
使用默认的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
是数字,似乎必须是实际名称。