Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an element from a JSON response

Tags:

json

c#

I have a JSON string from which I want to be able to delete some data.

Below is the JSON response:

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

From above JSON response I want to able remove the "ResponseType": "VirtualBill", part such that it looks like this:

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

Is there an easy way to do this in C#?

like image 683
vsreekanth Avatar asked Jun 27 '16 13:06

vsreekanth


1 Answers

Using Json.Net, you can remove the unwanted property like this:

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

Fiddle: https://dotnetfiddle.net/BgMQAE


If the property you want to remove is nested inside another object, then you just need to navigate to that object using SelectToken and then Remove the unwanted property from there.

For example, let's say that you wanted to remove the ConversionValue property, which is nested inside BillHeader, which is itself nested inside Response. You can do it like this:

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

Fiddle: https://dotnetfiddle.net/hTlbrt

like image 130
Brian Rogers Avatar answered Oct 03 '22 03:10

Brian Rogers