问题描述
如果我有一个 C# 模型类,JSON.net 使用它来绑定来自序列化 JSON 字符串的数据,有没有办法可以从该类创建查询字符串以发出初始请求?
If I have a C# model class that is used by JSON.net to bind data from a serialized JSON string, is there a way that I can create a query string from that class in order to make the initial request?
模型类示例:
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"参数.谢谢!
So the essence of what I am trying to do is gather both "id" and "some_string" from the model object so i can dynamically create a the "&fields" arguments. Thanks!
推荐答案
@Leigh Shepperson 有正确的想法;但是,您可以使用 LINQ 用更少的代码来完成.我会创建一个这样的辅助方法:
@Leigh Shepperson has the right idea; however, you can do it with less code using LINQ. I would create a helper method like this:
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>
一起使用:
If you're running under the 3.5 version of the .Net Framework such that you don't have the generic GetCustomAttribute<T>
method available to you, you can do the same thing with the non-generic GetCustomAttributes()
method instead, using it with SelectMany
and Cast<T>
:
return string.Join(",",
modelType.GetProperties()
.SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute))
.Cast<JsonPropertyAttribute>())
.Select(jp => jp.PropertyName)
.ToArray());
这篇关于从类中获取 JSON 属性名称列表以在查询字符串中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!