C#修改嵌套JSON数组指定元素attribute_value值的方法求助
修正JSON数组元素属性的解决方案
你代码里的语法确实有问题,核心是没搞对JSON数组的访问方式。what_changed是一个数组,得先通过索引定位到具体元素,再修改它的属性值。下面是用Newtonsoft.Json(Json.NET)实现的正确方案:
直接修改的简洁写法
using Newtonsoft.Json.Linq; // 你的原始JSON文本(已补全末尾缺失的闭合大括号,否则解析会报错) string jsonText = @"{""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 } ] }}"; // 解析JSON为JObject JObject jObj = JObject.Parse(jsonText); // 定位到第二个元素(索引1)并修改attribute_value jObj["audit_entry"]["what_changed"][1]["attribute_value"] = "你的新值"; // 输出修改后的JSON(如果需要) string updatedJson = jObj.ToString();
更清晰的分步写法(适合复杂场景)
如果JSON结构比较复杂,分步操作能让代码更易读、更不容易出错:
// 先获取what_changed数组(显式转换为JArray) JArray whatChangedArray = (JArray)jObj["audit_entry"]["what_changed"]; // 获取数组中的第二个元素(显式转换为JObject) JObject targetItem = (JObject)whatChangedArray[1]; // 修改目标属性值 targetItem["attribute_value"] = "新的subject_reference值";
关键说明
- 数组索引从0开始,所以第二个元素用
[1]访问 - 确保你的项目已经安装了Newtonsoft.Json NuGet包(这是
JObject和JArray的来源)
内容的提问来源于stack exchange,提问作者RShome
相关产品推荐
相关产品推荐

