从类中获取JSON属性名称的列表以在查询字符串中使用

从类中获取JSON属性名称的列表以在查询字符串中使用,第1张

从类中获取JSON属性名称的列表以在查询字符串中使用

@Leigh Shepperson有正确的主意;但是,您可以使用LINQ用更少的代码来实现。我将创建这样的辅助方法

using System.Linq;using System.Reflection;using Newtonsoft.Json;...public static string GetFields(Type modelType){    return string.Join(",",        modelType.GetProperties()      .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>())      .Select(jp => jp.PropertyName));}

您可以像这样使用它:

var fields = "&fields=" + GetFields(typeof(model));

编辑

如果您在.Net
framework的3.5版本下运行,而您没有

GetCustomAttribute<T>
可用的通用方法,则可以对非通用
GetCustomAttributes()
方法执行相同的 *** 作,而将其与
SelectMany
和一起使用
Cast<T>

    return string.Join(",",        modelType.GetProperties()      .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute))  .Cast<JsonPropertyAttribute>())      .Select(jp => jp.PropertyName)      .ToArray());


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5615297.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存