Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c# - Removing an element from a JSON response

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#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...