从JSON响应中删除元素 [英] Removing an element from a JSON response
问题描述
我有一个JSON字符串,我希望从该字符串中删除一些数据.
I have a JSON string from which I want to be able to delete some data.
以下是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",
部分看起来像这样:
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
}
在C#中有简单的方法吗?
Is there an easy way to do this in C#?
推荐答案
使用 Json.Net ,您可以这样删除不需要的属性:
Using Json.Net, you can remove the unwanted property like this:
JObject jo = JObject.Parse(json);
jo.Property("ResponseType").Remove();
json = jo.ToString();
提琴: 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.
例如,假设您要删除ConversionValue
属性,该属性嵌套在BillHeader
内部,而该属性本身嵌套在Response
内部.您可以这样做:
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();
提琴: https://dotnetfiddle.net/hTlbrt
这篇关于从JSON响应中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!