简体   繁体   English

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

[英]How to remove particular attribute from JSON string using C#

I have JSON string as below 我有JSON字符串如下

[{
        "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#. 如何使用C#从JSON字符串中删除attachments属性。 I am using JSON.net. 我正在使用JSON.net。

Using Linq 使用Linq

var jArr =  JArray.Parse(json);

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

var newJson = jArr.ToString();

or using anonymous classes 或使用匿名类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM