我在外部文件中有以下 JSON:
{
"Name": "Service Provider",
"Categories": [
{
"Name": "Identity",
"Mandatory": false
},
{
"Name": "Contat Information",
"Mandatory": false
},
{
"Name": "Service Fields",
"Mandatory": false
},
{
"Name": "Addresses",
"Mandatory": false
},
{
"Name": "Bank Accounts",
"Mandatory": false
}
]
}
例如,如果我想替换“身份”类别,使其在内存中看起来像这样:
{
"Name": "Identity",
"Mandatory": true,
...
}
我可以写这样的东西:
JObject jObject = return JsonConvert.DeserializeObject<JObject>(File.ReadAllText(path));
// "GetNewIdentity()" gets a JObject representing the new "Identity" JSON shown above
jObject["Categories"][0] = GetNewIdentity();
问题是我在编写代码时需要知道要更改哪个类别。如果我知道仅在运行时更改哪个类别怎么办?
这就是为什么我想使用其 Name
属性在数组中查找要替换的类别。我尝试过以下代码:
// "name" comes from a different place.
result["Categories"].Single(c => c["Name"].Equals(name)) = GetNewIdentity();
但是因为我尝试将值分配给返回值而不是变量,所以出现以下错误:
The left-hand side of an assignment must be a variable, property or indexer
我还希望在替换后保留类别的顺序。我怎样才能做到这一点?
注意:
我没有或可以拥有表示 JSON 的 POCO 类。
最佳答案
这是一个如何做到这一点的示例。您需要的是访问您想要的属性并替换它的值。
void Main()
{
JObject jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(path));
JObject newCategory = new JObject();
newCategory.Add("Name", "Identity");
newCategory.Add("Mandatory", "false");
newCategory.Add("NewProp", "Yes");
ReplaceCategoryValue(jObject, "Identity", newCategory);
Console.WriteLine(jObject.ToString());
}
void ReplaceCategoryValue(JObject jObject, string categoryName, JObject newCategory)
{
JToken categories = jObject["Categories"];
JObject targetCategory = categories.Children<JObject>().FirstOrDefault(x => x.Property("Name").Value.ToString() == categoryName);
targetCategory.Replace(newCategory);
}
关于c# - 根据项目中的属性替换数组项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946379/