【发布时间】:2016-10-05 08:06:30
【问题描述】:
我有一个这样的 JSON 字符串:
{"Country":"USA","States":["Chicago","Miami"]}
public string Remove(string json)
{
string[] stateFilter = { "Chicago", "Miami"};
foreach (var state in stateFilter)
{
//here I would like to create new copy of json for each state.
string newJson = {"Country":"USA","States":["Chicago"]} // Removed Miami from json for Chicago
}
}
现在我想通过在 JSON 中查找状态并将其从 JSON 字符串中删除来为每个状态创建一个新的 JSON 字符串。因此,每个状态都将包含其新的 JSON 副本,并且不会包含任何其他状态。
例如:Chicago 将在 JSON 中包含 Chicago States 属性。
我正在尝试的代码:
public string Remove(string json)
{
string[] stateFilter = { "Chicago", "Miami"};
foreach (var state in stateFilter)
{
var jArr = JArray.Parse(json);
jArr.Descendants().OfType<JProperty>()
.Where(p => p.Name == state)
.ToList()
.ForEach(att => att.Remove());
}
}
但是上面的代码从 JSON 字符串中移除了属性而不是值。
【问题讨论】:
标签: c# .net json linq json.net