【问题标题】:Is there a way to dynamically filter the JSON?有没有办法动态过滤 JSON?
【发布时间】:2021-11-09 21:33:38
【问题描述】:

我正在寻找一种根据来自 URL 的请求过滤 JObject 的方法。第二个代码块按预期工作并从响应中删除“Id”列:

我的 JObject:

JObject rss = new(
                    new JProperty("Name", name),
                    new JProperty("Surname",
                         new JArray(from p in data select p.sname)),
                    new JProperty("Id",
                         new JArray(from p in data select p.id)))

我尝试过的:

var fields = rss.Descendants()
                           .Where(x => x.Type == JTokenType.Property)
                           .Cast<JProperty>()
                           .Where(x => x.Name == "Id").ToList();
                foreach (var field in fields)
                {
                    field.Remove();
                } 

但是,我无法找到一种方法来执行此过程以删除请求的字段或仅返回所需的字段。除了 GraphQL 之外,还有什么方法可以做这种类型的过程吗?

【问题讨论】:

    标签: c# json asp.net-web-api json.net linq-to-json


    【解决方案1】:

    如果您想手动从 JObject 中删除属性,您可以执行以下操作:

    var requestedPaths = new[] { "Name" };
    foreach (var prop in rss.Descendants().OfType<JProperty>().ToList())
    {
        if (!requestedPaths.Contains(prop.Path))
        {
            prop.Remove();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2010-09-08
      • 2022-01-03
      • 2022-10-21
      • 2021-03-12
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多