【问题标题】:Errors updating Json with null array items使用空数组项更新 Json 时出错
【发布时间】:2011-11-18 21:51:21
【问题描述】:

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

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 是一个空数组)

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

       }

【问题讨论】:

  • 已删除.. 这更重要。
  • 我真的不明白mvc 标签与你的问题有什么关系。
  • 您使用哪种 JSON 实现?
  • 我正在使用 RavenDB 文档...我不确定什么 json 实现..

标签: c# json patch ravendb


【解决方案1】:

修补命令希望数据存在,因此您需要使用索引来查找没有空 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
                          {
                               .........

我创建了一个full code sample,有任何问题请告诉我。

【讨论】:

    【解决方案2】:

    看起来您正在尝试在数组上设置属性,但数组没有属性,它们只能包含其他对象。

    【讨论】:

    • 那么在这种情况下我该怎么做呢?我想更改“特权”数组中的“级别”值......有不同的语法吗?感谢您的帮助。
    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多