我有以下JSON
[
{
"Code": "Global Payroll",
"Month1": 1,
"Month2": 0,
"Month3": 0,
"Month4": null,
"Month5": null,
"Month6": null,
"Month7": null,
"Month8": null,
"Month9": null,
"Month10": null,
"Month11": null,
"Month12": null,
"YTD": 1,
"PercentOfTotal": "16.67%"
},
{
"Code": "GV Payroll",
"Month1": 0,
"Month2": 0,
"Month3": 3,
"Month4": null,
"Month5": null,
"Month6": null,
"Month7": null,
"Month8": null,
"Month9": null,
"Month10": null,
"Month11": null,
"Month12": null,
"YTD": 3,
"PercentOfTotal": "50.00%"
}
]
我想做的是以某种方式从JSON中删除Month4,Month5等,然后将其转换回字符串。
我尝试研究JArray.remove方法,但这会从数组中删除项目本身。有人可以告诉我如何从JArray完全删除属性。
答案 0 :(得分:1)
JArray用于[]
(数组)
JObject用于{}
(对象)
Month1 .. Month12
它们都是对象。在这种情况下,您需要使用JObject
JArray ja = JArray.Parse(json);
JObject jo = (JObject)ja[0];
jo.Property("Month4").Remove();
json = jo.ToString();
答案 1 :(得分:1)
var array = JArray.Parse(json);
foreach (JObject elem in array)
{
foreach (var elementToRemove in new List<string>() {"Month4", "Month5" })
{
elem.Property(elementToRemove).Remove();
}
}
var resultJson = array.ToString();
答案 2 :(得分:1)
您可以从Remove()
致电JProperty
将其删除。另外,您可能只想删除值为空的名为“ MonthX”的属性,而不是按名称删除特定属性。
var json = /* your json here */;
var payrolls = JArray.Parse(json);
foreach(var payroll in payrolls)
{
foreach (var property in payroll.Children<JProperty>().ToArray())
{
if (property.Name.StartsWith("Month") && property.Value.Type == JTokenType.Null)
property.Remove();
}
}
json = payrolls.ToString();