C# 使用空数组项更新Json时出错
我正在通过代码修改Json文档。Json具有数组嵌套项。我的代码失败了,因为我认为它无法处理特定数组为空的Json文档。如何检查null或空数组,并使此代码仅适用于具有数据的数组C# 使用空数组项更新Json时出错,c#,json,patch,ravendb,C#,Json,Patch,Ravendb,我正在通过代码修改Json文档。Json具有数组嵌套项。我的代码失败了,因为我认为它无法处理特定数组为空的Json文档。如何检查null或空数组,并使此代码仅适用于具有数据的数组 store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", new IndexQuery { Query = "Tag:patrons" }, new[] { new PatchRequest { Type
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:patrons" },
new[]
{
new PatchRequest
{
Type = PatchCommandType.Modify,
Name = "Privilege",
Nested = new[]
{
new PatchRequest {Type = PatchCommandType.Set, Name="Level",
Value="Gold"},
}
}
}, allowStale: false);
Json文档如下所示:
{
"Privilege": [{
"Level": "Gold",
"Code": "12312",
"EndDate": "12/12/2012"
}],
"Phones": [{
"Cell": "123123",
"Home": "9783041284",
"Office": "1234123412"
}]
"MiddleInitial":"F"
}
一些Json文档可能看起来像(注意,在本例中特权是一个空数组)
看起来您正试图在数组上设置属性,但数组没有属性,它们只能包含其他对象。修补命令要求数据在其中,因此您需要使用索引来查找没有空
特权列表的文档
首先,您需要这样一个索引:
public override IndexDefinition CreateIndexDefinition()
{
return new IndexDefinitionBuilder<Patron>
{
Map = docs => from doc in docs
where doc.Privileges != null
select new { HasPrivileges = doc.Privileges.Count == 0 ? false : true }
}.ToIndexDefinition(Conventions);
}
我已经创建了一个,如果有任何问题,请告诉我。可能的重复项已删除。。这更切题了。我真的不明白mvc
标记与您的问题有什么关系。您使用哪个JSON实现?我使用的是RavenDB文档。。。我不确定json实现是什么..那么在这种情况下我该怎么做呢?我想更改“privilege”数组中的“level”值。。。有不同的语法吗?谢谢你的帮助。
public override IndexDefinition CreateIndexDefinition()
{
return new IndexDefinitionBuilder<Patron>
{
Map = docs => from doc in docs
where doc.Privileges != null
select new { HasPrivileges = doc.Privileges.Count == 0 ? false : true }
}.ToIndexDefinition(Conventions);
}
store.DatabaseCommands.UpdateByIndex("PatronByPrivilege",
//Only apply the patch to Patrons that have a privilege
new IndexQuery { Query = "HasPrivileges:true" },
new[]
{
new PatchRequest
{
.........