8

I have JSON string as below

[{
        "attachments": [{ "comment": "communication", "comment_date_time": "2035826"} ], 
        "spent_hours": "4.00", 
        "description": ""       
    }, 
   {
        "attachments": [], 
        "spent_hours": "4.00", 
        "description": ""       
    }]

How can i remove the attachments attribute from the JSON string using C#. I am using JSON.net.

4

1 回答 1

22

使用 Linq

var jArr =  JArray.Parse(json);

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

var newJson = jArr.ToString();

或使用匿名类

var anon = new[] { new{spent_hours="", description=""} };
var newJson = JsonConvert.SerializeObject(
                         JsonConvert.DeserializeAnonymousType(json, anon));
于 2013-05-28T06:58:39.497 回答