我有一个 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();
fiddle :https://dotnetfiddle.net/BgMQAE
如果您要删除的属性嵌套在另一个对象中,那么您只需使用SelectToken
导航到该对象即可。然后从那里删除
不需要的属性。
例如,假设您要删除嵌套在 BillHeader
中的 ConversionValue
属性,它本身嵌套在 Response
中.你可以这样做:
JObject jo = JObject.Parse(json);
JObject header = (JObject)jo.SelectToken("Response.BillHeader");
header.Property("ConversionValue").Remove();
json = jo.ToString();
fiddle :https://dotnetfiddle.net/hTlbrt
关于c# - 从 JSON 响应中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054986/