我在外部文件中具有以下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
}
]
}
例如,如果我想替换“ Identity”类别,使其在内存中看起来像这样:
{
"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类。
答案 0 :(得分:1)
我仍然不明白为什么您不定义POCO。这里看看这个。 这是您的POCOS
public class MyRootObject
{
public string Name { get; set; }
public List<Category> Categories { get; set; }
}
public class Category
{
public string Name { get; set; }
public bool Mandatory { get; set; }
}
这就是您的使用方式
var rootObject = JsonConvert.DeserializeObject<MyRootObject>(Resource.Json);
//name comes from somewhere else like in the question
var identity = rootObject.Categories.Single(c => c.Name == name);
identity.Mandatory = GetNewIdentity();
答案 1 :(得分:1)
这是一个示例,您可以如何做。您需要访问所需的属性并替换其值。
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);
}