繁体   English   中英

从JSON响应中删除元素

[英]Removing an element from a JSON response

我有一个JSON字符串,我希望能够删除一些数据。

以下是JSON响应:

{
  "ResponseType": "VirtualBill",
  "Response": {
    "BillHeader": {
      "BillId": "7134",
      "DocumentId": "MN003_0522060",
      "ConversionValue": "1.0000",
      "BillType": "Vndr-Actual",
      "AccountDescription": "0522060MMMDDYY",
      "AccountLastChangeDate": "06/07/2016"
    }
  },
  "Error": null
}

从上面的JSON响应我想删除"ResponseType": "VirtualBill",部分使得它看起来像这样:

{
  "Response": {
    "BillHeader": {
      "BillId": "7134",
      "DocumentId": "MN003_0522060",
      "ConversionValue": "1.0000",
      "BillType": "Vndr-Actual",
      "AccountDescription": "0522060MMMDDYY",
      "AccountLastChangeDate": "06/07/2016"
    }
  },
  "Error": null
}

有没有一种简单的方法在C#中执行此操作?

使用Json.Net ,您可以删除不需要的属性,如下所示:

JObject jo = JObject.Parse(json);
jo.Property("ResponseType").Remove();
json = jo.ToString();

小提琴: https//dotnetfiddle.net/BgMQAE


如果要删除的属性嵌套在另一个对象中,则只需使用SelectToken导航到该对象,然后从那里Remove不需要的属性。

例如,假设您要删除ConversionValue属性,该属性嵌套在BillHeader ,该属性本身嵌套在Response 你可以这样做:

JObject jo = JObject.Parse(json);
JObject header = (JObject)jo.SelectToken("Response.BillHeader");
header.Property("ConversionValue").Remove();
json = jo.ToString();

小提琴: https//dotnetfiddle.net/hTlbrt

将其转换为JsonObject ,删除密钥,然后将其转换回string

Sample sample= new Sample();
 var     properties=sample.GetType().GetProperties().Where(x=>x.Name!="ResponseType");
 var response = new Dictionary<string,object>() ;

foreach(var prop in properties)
 {
    var propname = prop.Name;
   response[propname] = prop.GetValue(sample); ;
}

 var response= Newtonsoft.Json.JsonConvert.SerializeObject(response);

暂无
暂无

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

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