从类中获取要在查询字符串中使用的 JSON 属性名称列表 [英] Get a list of JSON property names from a class to use in a query string

查看:29
本文介绍了从类中获取要在查询字符串中使用的 JSON 属性名称列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 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 方法,您可以使用非通用的 GetCustomAttributes() 方法,将其与 SelectManyCast 一起使用:

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 属性名称列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆