如何使用C#从JSON字符串中删除特定属性

Ira*_*ppa 7 c# json

我有JSON如下字符串

[{
        "attachments": [{ "comment": "communication", "comment_date_time": "2035826"} ], 
        "spent_hours": "4.00", 
        "description": ""       
    }, 
   {
        "attachments": [], 
        "spent_hours": "4.00", 
        "description": ""       
    }]
Run Code Online (Sandbox Code Playgroud)

如何使用C#attachmentsJSON字符串中删除属性.我正在使用JSON.net.

I4V*_*I4V 20

使用Linq

var jArr =  JArray.Parse(json);

jArr.Descendants().OfType<JProperty>()
                  .Where(p => p.Name == "attachments")
                  .ToList()
                  .ForEach(att=>att.Remove());

var newJson = jArr.ToString();
Run Code Online (Sandbox Code Playgroud)

或使用匿名类

var anon = new[] { new{spent_hours="", description=""} };
var newJson = JsonConvert.SerializeObject(
                         JsonConvert.DeserializeAnonymousType(json, anon));
Run Code Online (Sandbox Code Playgroud)