我有一个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#中有一种简单的方法吗?
答案 0 :(得分:9)
使用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();
答案 1 :(得分:0)
将其转换为JsonObject
,删除密钥,然后将其转换回string
。
答案 2 :(得分:-1)
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);
答案 3 :(得分:-2)
这是解决方案。
var temp={"ResponseType": "VirtualBill", "Response": { "BillHeader": { "BillId": "7134", "DocumentId": "MN003_0522060", "ConversionValue": "1.0000", "BillType": "Vndr-Actual", "AccountDescription": "0522060MMMDDYY", "AccountLastChangeDate": "06/07/2016" } }, "Error": null };
delete temp.ResponseType;
JSON.stringify(temp);
这将提供输出:
“{” 响应 “:{” BillHeader “:{” BILLID “:” 7134" , “DocumentId”: “MN003_0522060”, “ConversionValue”: “1.0000”, “BillType”: “Vndr-实际”,” AccountDescription “:” 0522060MMMDDYY “ ”AccountLastChangeDate“: ”2016年6月7日“}}, ”错误“:NULL}”