我在外部文件中有以下 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();
但是因为我试图将值分配给返回值而不是变量,所以我收到以下错误:
赋值的左侧必须是变量、属性或索引器
我还希望在替换后保留类别的顺序。我怎样才能做到这一点?
笔记:
我没有或可以有代表 JSON 的 POCO 类。