从JSON中删除元素

时间:2014-08-26 16:01:40

标签: c# json

我有这样的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

中添加或删除项目

1 个答案:

答案 0 :(得分:2)

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();