【问题标题】:Update a value of a key value pair in a nested array in C#在 C# 中更新嵌套数组中键值对的值
【发布时间】:2020-10-19 22:02:58
【问题描述】:

我有以下 json

  {"audit_entry": {
    "where_uri": "test.com/service/apps/171f0841-825b-4964-8f8c-0869650f14a6",
    "why_uri": "test.com/service/reference/reasons_for_change/43545kjhjhkj0869650f14a6",
    "who_uri": "test.com/service/users/4977dae1-a307-425f-980c-53413fef1b0f",
    "when_audited": "2018-11-13T20:20:39+00:00",
    "what_uri": "test.com/service/subjects/1bc67a71-8549-4ab8-9dd9-e44238198860",
    "what_changed": [
        {
            "attribute_name": "birth_year",
            "attribute_value": "1969",
            "attribute_change": null
        },
        {
            "attribute_name": "subject_reference",
            "attribute_value": "dsdsfg",
            "attribute_change": null
        }
        ]
    }

我希望能够在 what_changed 的​​第二个孩子中更改“attribute_value”的值。即索引 [1]。我试过以下代码:

        JObject jObj = JObject.Parse(jsonText);
        jObj["audit_entry"]["what_changed"]["attribute_name"[1]];

但我知道我的语法有问题。 任何想法将不胜感激。谢谢

【问题讨论】:

  • 首先尝试编写代码,将每个索引器调用分配给变量(你知道"attribute_name"[1]'t' 吗?)
  • 谢谢,我不是开发人员,所以恐怕我不知道该怎么做。
  • 这里是 Getting values by Property Name or Collection Index 上使用 Jobject 的文档

标签: c# api automation


【解决方案1】:

这是使用JObjectGetting values by Property Name or Collection Index 的文档。

你可以在代码示例中看到索引的用法:

string itemTitle = (string)rss["channel"]["item"][0]["title"];

在你的代码示例中应该是:

var toto = (string)jObj["audit_entry"]["what_changed"][1]["attribute_name"];

Live example

您可以使用Modifying JSON作为参考进行修改:

jObj["audit_entry"]["what_changed"][1]["attribute_name"] = "New Value";

【讨论】:

  • 非常感谢,这太棒了!
猜你喜欢
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 2011-07-02
  • 2017-04-04
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
相关资源
最近更新 更多