Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize an object into query-string format?

How do I serialize an object into query-string format? I can't seem to find an answer on google. Thanks.

Here is the object I will serialize as an example.

public class EditListItemActionModel {     public int? Id { get; set; }     public int State { get; set; }     public string Prefix { get; set; }     public string Index { get; set; }     public int? ParentID { get; set; } } 
like image 314
Benjamin Avatar asked Jul 27 '11 17:07

Benjamin


People also ask

What is serialize query?

A library for simplifying encoding and decoding URL query parameters.

Can we send object in query string C#?

But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.


1 Answers

I'm 99% sure there's no built-in utility method for this. It's not a very common task, since a web server doesn't typically respond with a URLEncoded key/value string.

How do you feel about mixing reflection and LINQ? This works:

var foo = new EditListItemActionModel() {   Id = 1,   State = 26,   Prefix = "f",   Index = "oo",   ParentID = null };  var properties = from p in foo.GetType().GetProperties()                  where p.GetValue(foo, null) != null                  select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(foo, null).ToString());  // queryString will be set to "Id=1&State=26&Prefix=f&Index=oo"                   string queryString = String.Join("&", properties.ToArray()); 

Update:

To write a method that returns the QueryString representation of any 1-deep object, you could do this:

public string GetQueryString(object obj) {   var properties = from p in obj.GetType().GetProperties()                    where p.GetValue(obj, null) != null                    select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());    return String.Join("&", properties.ToArray()); }  // Usage: string queryString = GetQueryString(foo); 

You could also make it an extension method without much additional work

public static class ExtensionMethods {   public static string GetQueryString(this object obj) {     var properties = from p in obj.GetType().GetProperties()                      where p.GetValue(obj, null) != null                      select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());      return String.Join("&", properties.ToArray());   } }  // Usage: string queryString = foo.GetQueryString(); 
like image 125
Dave Ward Avatar answered Sep 26 '22 02:09

Dave Ward