Wednesday, 11 September 2013

c# convert class to query string

c# convert class to query string

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

No comments:

Post a Comment