从JSON中删除元素

本文关键字:元素 删除 JSON | 更新日期: 2023-09-27 18:19:25

JSON是这样的:

   {
"flight" : [ 
   {    
            "arv" : { 
        "@aptCode" : "JFK"
        },
            "legs" : { "@count" : "1",
                "leg" : { "@arvDayIndicator" : "0",
                    "@wetLease" : "False",
                    "mealCodes" : "M M M M M M M M M M M M M M M M M M M M M M",
                    "operation" : { "@acftOwner" : "",
                        "@operatedBy" : ""
                      }                        
                  }
              }
          },
      { 
            "arv" : { "@aptCode" : "LHR" },
            "legs" : { "@count" : "2",
                "leg" : { "@arvDayIndicator" : "0",
                    "@wetLease" : "False",
                    "mealCodes" : "M M M M M M M M M M M M M f M M f M M M f M",
                    "operation" : { "@acftOwner" : "",
                        "@operatedBy" : ""
                      }                       
                  }
              }
          }]}

如何删除内部值,如:

"@wetLease"、"mealCodes"或"@operatedBy"

我试着:

jSon.SelectToken(@"flight[0].arv").Remove();

为第一个实例,但给我下一个错误:

无法从Newtonsoft.Json.Linq.JProperty中添加或删除项

从JSON中删除元素

var names = new List<string>(){"@wetLease","mealCodes" , "@operatedBy"};
var jObj = JObject.Parse(json);
jObj.Descendants().OfType<JProperty>()
    .Where(p=>names.Contains(p.Name))
    .ToList()
    .ForEach(p=>p.Remove());
var newjson = jObj.ToString();