使用空数组项更新Json时出错

本文关键字:Json 出错 更新 数组 | 更新日期: 2023-09-27 18:15:04

我正在通过代码修改Json文档。Json具有数组嵌套项。我的代码是失败的,因为我相信它不能处理Json文档,其中特定的数组是空的。如何检查null或空数组,并使此代码仅适用于具有数据的数组?

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文档可能看起来像(注意特权是一个空数组在这种情况下)

 {
         "Privilege": [],
         "Phones":    [{
                       "Cell": "123123",
                       "Home": "9783041284",
                       "Office": "1234123412"
                      }]
         "MiddleInitial":"F"
       }

使用空数组项更新Json时出错

补丁命令期望数据在那里,所以您需要使用索引来查找没有空Privileges列表的文档。

首先你需要一个像这样的索引:

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

然后你只应用补丁到文档中HasPrivileges = true,像这样:

store.DatabaseCommands.UpdateByIndex("PatronByPrivilege",
              //Only apply the patch to Patrons that have a privilege
              new IndexQuery { Query = "HasPrivileges:true" },
                     new[]
                     {
                          new PatchRequest
                          {
                               .........

我已经创建了一个完整的代码示例,有任何问题请告诉我。

看起来你是在尝试设置一个数组的属性,但是数组没有属性,它们只能包含其他对象。