从JSON响应中删除元素 [英] Removing an element from a JSON response

查看:118
本文介绍了从JSON响应中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆