如果我有一个 C# 模型类,JSON.net 使用它来绑定(bind)来自序列化 JSON 字符串的数据,有没有一种方法可以从该类创建查询字符串以发出初始请求?
模型类示例:
public class model
{
[JsonProperty(PropertyName = "id")]
public long ID { get; set; }
[JsonProperty(PropertyName = "some_string")]
public string SomeString {get; set;}
}
查询字符串示例:
baseUrl + uri + "&fields=id,some_string" + token
所以我要做的本质是从模型对象中收集“id”和“some_string”,这样我就可以动态创建“&fields”参数。谢谢!
最佳答案
@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());
关于c# - 从类中获取 JSON 属性名称列表以在查询字符串中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616005/