Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert class to query string

Tags:

c#

Im trying to convert a few classes/objects in my application to a query string for example:

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; }
}

would then become:

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

Which i am achieving with the following function

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('&');
}

but If I pass a list into the function it will also include the Count and Capacity properties and other thing I dont want. Say its a list of

List<otherclass>()

Cheers

like image 835
Yes Avatar asked Oct 27 '25 10:10

Yes


2 Answers

Seems pretty simple to me, check if the class is an IEnumerable or IEnumerator and if so Enumerate it (rather than reflecting that particular class). It would help if you explained how you'd like us to deal with such results.

//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('&');
}
like image 96
NPSF3000 Avatar answered Oct 30 '25 00:10

NPSF3000


I don't get the point, why you are trying it complicated like that?

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; }
}

... or did you miss something in your question?

like image 34
dognose Avatar answered Oct 30 '25 00:10

dognose