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

标签 c# json json.net .net-3.5 query-string

如果我有一个 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/

相关文章:

c# - HttpWebRequest 是否自动发送 200 OK?

c# - 使用代理在 C# 中拦截方法调用

mysql - Mysql Json 列中的增量 JSON 字段导致浮点而不是整数

asp.net-web-api - 方法未找到 : 'Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)' (webapi and PCL)

c# - MSBuild 正在用旧版本替换 Newtonsoft.Json.dll

c# - 将 WPF DataGrid 绑定(bind)到 List<Interface>

c# - ASP.NET - CSS 到 ImageButton 下的中心标签?

带有 JSON 对象的 JavaScript 作用域

iphone - 将 JSON 数据从 NSData 转换为 NSDictionary

c# - 如何防止 Json.NET 对缺少的构造函数参数使用默认值,同时仍然对属性使用默认值?