c# - 如何以编程方式从动态 JObject 中删除属性

标签 c# .net json.net deserialization

下面是代码

json - 只需要响应中的 JsonLookupData

{
  "LookupType": "ABC",
  "BusSegmentName": "Test",
  "PolcyObjectId": "999",
  "JsonLookupData": {
    "data":    {
      "OBJ_ID": "9393",
      "ABC": "JAJA",
      "XYZ": "LL",
      "AAA": "250.00"
    }
  }
}

public new dynamic input { get; set; }

//initialization 
 input = JsonConvert.DeserializeObject(jsonInput.ToString());

//trying to remove all attributes except JsonLookupData
input.Properties().Where
                 (x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());
  

有没有办法直接从动态输入中删除属性(不想先将其分配给 JObject)。

上面的代码给出了下面的错误

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

最佳答案

虽然 JObject 仍然是正确的选择,但您仍然可以使用 dynamic只要您不使用依赖于动态调度的 lambda 表达式即可。

通过分配 input.Properties() 的输出对于非动态类型( IEnumerable<dynamic> ),我们可以在 lambda 表达式中执行操作。

input = JsonConvert.DeserializeObject(jsonInput.ToString());

IEnumerable<dynamic> props = input.Properties();
props.Where(x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());

string xx = JsonConvert.SerializeObject(input);

输出:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

或者,您可以完全避免使用 Linq。

input = JsonConvert.DeserializeObject(jsonInput);

// create a separate tracking collection so that we 
// do not modify the collection we are iterating
var propsToRemove = new List<JProperty>();

foreach (var prop in input.Properties())
{
    if (!prop.Name.Equals("JsonLookupData"))
    {
        propsToRemove.Add(prop);
    }
}

propsToRemove.ForEach(x => x.Remove());

string xx = JsonConvert.SerializeObject(input);

输出:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

用于您的示例 JSON。

关于c# - 如何以编程方式从动态 JObject 中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68820134/

相关文章:

SelectTokens中的JSON.Net "Could not read query operator"

c# - Selenium - 发送 key 以在影子根(打开)和挪威 BankId 的多个 iframe 中输入密码

c# - 为扩展方法创建特定于硬件的委托(delegate)

c# - 为什么在调用者而不是有问题的行上抛出异常

.net - 为什么 .NET "application settings"没有存储在注册表中?

c# - 我如何才能知道我的桌面程序是否正在控制台上运行?

C#:有什么工具可以自动从类生成接口(interface)?

c# - JSON.NET:如何根据父(持有者)对象值反序列化接口(interface)属性?

c# - MVVM Light SimpleIoC 与 Ninject

c# - Json.Net JObject 的 Automapper 反射错误