首页 > 解决方案 > 在 C# 中更新嵌套数组中键值对的值

问题描述

我有以下 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]];

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

标签: c#apiautomation

解决方案


这是有关使用属性名称或集合索引获取值JObject的文档。

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

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

在您的代码示例中,它应该是:

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

活生生的例子

您可以使用修改 JSON作为修改的参考:

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

推荐阅读