c#将类转换为查询字符串

时间:2013-09-11 23:54:27

标签: c#

我试图将应用程序中的几个类/对象转换为查询字符串,例如:

public class LoginRequest : BaseRequest
{
    public string username { get; set; }
    public string password { get; set; }
    public otherclass d { get; set; }
}

public class otherclass
{
    public string a { get; set; }
    public string b { get; set; }
}

然后会变成:

username=test&password=p&a=123&b=123

我使用以下功能实现了

private string ObjectToQueryString<T>(T obj) where T: class {
    StringBuilder sb = new StringBuilder();
    Type t = obj.GetType();

    var properties = t.GetProperties();
    foreach (PropertyInfo p in properties)
    {
        if (p.CanRead)
        {
            var indexes = p.GetIndexParameters();
            if (indexes.Count() > 0)
            {
                var pp = p.GetValue(obj, new object[] { 1 });
                sb.Append(ObjectToQueryString(pp));
            }
            else
            {

                //I dont think this is a good way to do it
                if (p.PropertyType.FullName != p.GetValue(obj, null).ToString())
                {
                    sb.Append(String.Format("{0}={1}&", p.Name, HttpUtility.UrlEncode(p.GetValue(obj, null).ToString())));
                }
                else
                {
                    sb.Append(ObjectToQueryString(p.GetValue(obj, null)));
                }
            }
        }
    }

    return sb.ToString().TrimEnd('&');
}

但如果我将一个列表传递给该函数,它还将包括Count和Capacity属性以及其他我不想要的东西。说出一个

列表
List<otherclass>()

干杯

3 个答案:

答案 0 :(得分:2)

我不明白这一点,为什么你这么复杂呢?

public class LoginRequest : BaseRequest
{
    public string username { get; set; }
    public string password { get; set; }
    public otherclass d { get; set; }

    public String getQueryString(){
      return "username="+this.username+"&password="+this.password+"&a="+this.d.a+"&b="+this.d.b;
    }
}

public class otherclass
{
    public string a { get; set; }
    public string b { get; set; }
}

...或者你错过了一些问题?

答案 1 :(得分:1)

对我来说似乎很简单,检查该类是IEnumerable还是IEnumerator,如果是,请枚举它(而不是反映那个特定的类)。如果您解释了您希望我们如何处理此类结果,那将会有所帮助。

//username=bob&password=123&a=Cheese&b=Chocolate&a=Cat&b=Dog

public class LoginRequest
{
    public string username { get; set; }
    public string password { get; set; }
    public List<OtherClass> d { get; set; }
}

public class OtherClass
{
    public string a { get; set; }
    public string b { get; set; }
}

static void Main(string[] args)
{
    var request = new LoginRequest
    {
        username = "bob",
        password = "123",
        d = new List<OtherClass> { new OtherClass { a = "Cheese", b = "Chocolate" } ,
        new OtherClass { a = "Cat", b = "Dog" } }
    };

    Console.WriteLine(ObjectToQueryString(request));
    Console.ReadLine();
}

private static string ObjectToQueryString<T>(T obj) where T : class
{
    StringBuilder sb = new StringBuilder();

    IEnumerable data = obj as IEnumerable ?? new[] { obj };

    foreach (var datum in data)
    {
        Type t = datum.GetType();
        var properties = t.GetProperties();
        foreach (PropertyInfo p in properties)
        {
            if (p.CanRead)
            {
                var indexes = p.GetIndexParameters();
                if (indexes.Count() > 0)
                {
                    var pp = p.GetValue(datum, new object[] { 1 });
                    sb.Append(ObjectToQueryString(pp));
                }
                else if (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType  != typeof(string))
                {
                    sb.Append(ObjectToQueryString(p.GetValue(datum)));
                }
                else
                {

                    //I dont think this is a good way to do it
                    if (p.PropertyType.FullName != p.GetValue(datum, null).ToString())
                    {
                        //sb.Append(String.Format("{0}={1}&", p.Name, HttpUtility.UrlEncode(p.GetValue(datum, null).ToString())));
                        sb.Append(String.Format("{0}={1}&", p.Name, p.GetValue(datum, null).ToString()));
                    }
                    else
                    {
                        sb.Append(ObjectToQueryString(p.GetValue(datum, null)));
                    }
                }
            }
        }
    }
    return sb.ToString().TrimEnd('&');
}

答案 2 :(得分:0)

使用GetProperties()

的BindingFlags参数

http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags%28v=vs.71%29.aspx

GetProperties(BindingFlags.DeclaredOnly | ...)

将其结果限制为您的类型声明的属性。