{"id":103713,"date":"2023-12-24T10:23:10","date_gmt":"2023-12-24T09:23:10","guid":{"rendered":"https:\/\/code-maze.com\/?p=103713"},"modified":"2024-01-09T15:02:45","modified_gmt":"2024-01-09T14:02:45","slug":"csharp-serialize-object-into-query-string","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/","title":{"rendered":"How to Serialize an Object into Query String Format in C#"},"content":{"rendered":"<p>In this article, we will learn how to serialize an object into query string format using C#. We will discuss the challenges we face when dealing with nested objects and arrays and how to deal with them.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/dotnet-querystrings\/SerializeObjectToQueryString\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p><a href=\"https:\/\/code-maze.com\/serialization-deserialization-csharp\/\" target=\"_blank\" rel=\"noopener\">Serialization<\/a> is a crucial concept in programming, particularly in C#. It involves converting the state of an object into a format such as a stream of bytes and actively storing or transmitting it.<\/p>\n<p>Transforming objects into a query string format becomes essential, especially in web development. Query strings, which consist of key-value pairs appended to a URL, are fundamental for passing parameters between the client and server in HTTP requests.<\/p>\n<p>Before we dive into this topic, we recommend going through <a href=\"https:\/\/code-maze.com\/how-to-create-a-url-query-string\/\" target=\"_blank\" rel=\"noopener\">how to create a URL query string<\/a>.<\/p>\n<h2><a id=\"serializing-an-object-into-a-query-string-using-reflection\"><\/a>Serialize an Object Into a Query String Using Reflection<\/h2>\n<p>In the context of C# programming, transforming objects into query string format involves converting the properties of an object into key-value pairs appended to a URL.<\/p>\n<p>Serialization using reflection involves dynamically inspecting and extracting the properties of an object at runtime and then creating key-value pairs from those properties to form a query string.<\/p>\n<p><a href=\"https:\/\/code-maze.com\/csharp-reflection\/\" target=\"_blank\" rel=\"noopener\">Reflection<\/a> is a powerful feature in C# that<strong> allows developers to inspect and interact dynamically with types and objects.<\/strong><\/p>\n<p>To start with, we&#8217;ll create a <code>Book<\/code> model class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Book\r\n{\r\n    public string Author { get; set; } = \"George Orwell\";\r\n    public string Language { get; set; } = \"English\";\r\n}<\/pre>\n<p>Now, let&#8217;s create a method to serialize an instance of the <code>Book<\/code> class into a query string using reflection:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static string ToQueryStringUsingReflection&lt;T&gt;(T obj)\r\n{\r\n    var properties = from p in obj?\r\n                            .GetType()\r\n                            .GetProperties()\r\n                     where p.GetValue(obj, null) != null\r\n                     select $\"{HttpUtility.UrlEncode(p.Name)}\" +\r\n                     $\"={HttpUtility.UrlEncode(p.GetValue(obj)?.ToString())}\";\r\n\r\n    return string.Join(\"&amp;\", properties);\r\n}<\/pre>\n<p>Here we define a generic <code>ToQueryStringUsingReflection&lt;T&gt;()<\/code> method that accepts an object of type <code>T<\/code> as the input parameter. After that, using reflection, we get the object&#8217;s properties and filter out any that are <code>null<\/code>. With the help of the <code>HttpUtility.UrlEncode()<\/code> method, we create a selection of key-value pairs by combining URL-encoded property names and values using the <code>select<\/code> LINQ clause.\u00a0 Lastly, we join the key-value pairs into a single string, using &#8220;&amp;&#8221; as a separator with the help of <code>string.Join()<\/code>.\u00a0<\/p>\n<p><strong>It is important to note, that since we are creating a query string, we must ensure that we properly encode both the keys and values of each query parameter.<\/strong>\u00a0<\/p>\n<p>Now, let&#8217;s create a method to construct the complete URL:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string CreateURLWithBookAsQueryParamsUsingReflection(string url, Book book)\r\n{\r\n    var queryParams = ToQueryStringUsingReflection(book);\r\n\r\n    return $\"{url}?{queryParams}\";\r\n}<\/pre>\n<p>Here, we define a <code>CreateURLWithBookAsQueryParamsUsingReflection()<\/code> method that accepts <code>url<\/code> and <code>book<\/code> object as the input parameters. Then, we call the <code>ToQueryStringUsingReflection()<\/code> method, and concatenate the <code>url<\/code> and <code>book<\/code> to form the complete URL.<\/p>\n<p>Let&#8217;s proceed to invoke the method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var baseApiUrl = \"https:\/\/test.com\";\r\nConsole.WriteLine(QueryStringSerializer.CreateURLWithBookAsQueryParamsUsingReflection(BaseApiUrl, new Book()));<\/pre>\n<p>Here, we initialize the <code>BaseApiUrl<\/code> and call the <code>CreateURLWithBookAsQueryParamsUsingReflection()<\/code> method to obtain the complete URL.<\/p>\n<p>Let&#8217;s check the final URL:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">https:\/\/test.com?Author=George+Orwell&amp;Language=English<\/code><\/p>\n<p>Here is the final URL with the query parameters.<\/p>\n<h2><a id=\"serializing-an-object-into-a-query-string-with-newtonsoft.json\"><\/a>Serialize an Object Into a Query String With Newtonsoft.Json<\/h2>\n<p><a href=\"https:\/\/www.newtonsoft.com\/json\" target=\"_blank\" rel=\"nofollow noopener\">Newtonsoft.Json<\/a>, commonly called <strong>Json.NET<\/strong>, is a popular third-party library for JSON serialization and deserialization in .NET applications.<\/p>\n<p>It provides a versatile and efficient way to work with JSON data, making it a widely adopted choice for developers. In the context of serializing an object into a query string, Json.NET offers a straightforward and robust solution.<\/p>\n<p>First, let&#8217;s install the <code>Newtonsoft.Json<\/code> package:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Install-Package Newtonsoft.Json<\/code><\/p>\n<p>Next, let&#8217;s create a new method in the <code>QueryStringSerializer<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static string ToQueryStringUsingNewtonsoftJson&lt;T&gt;(T obj)\r\n{\r\n    string jsonString = JsonConvert.SerializeObject(obj);\r\n\r\n    var jsonObject = JObject.Parse(jsonString);\r\n\r\n    var properties = jsonObject\r\n        .Properties()\r\n        .Where(p =&gt; p.Value.Type != JTokenType.Null)\r\n        .Select(p =&gt;\r\n            $\"{HttpUtility.UrlEncode(p.Name)}={HttpUtility.UrlEncode(p.Value.ToString())}\");\r\n\r\n\r\n    return string.Join(\"&amp;\", properties);\r\n}<\/pre>\n<p>In a similar fashion to our reflection method, we start by creating a generic <code>ToQueryStringUsingNewtonsoftJson()<\/code> method. Next, we serialize the object into a JSON string using <code>JsonConvert.SerializeObject()<\/code>.<\/p>\n<p>We then parse the JSON string into a <code>JObject<\/code> to extract key-value pairs. Similarly, while excluding <code>null<\/code> values, we create URL-encoded key-value pairs by combining property names and property values. Once again, our final step is to create the query string by joining our key-value pairs with <code>string.Join()<\/code> using &#8220;&amp;&#8221; as our separator.<\/p>\n<p>Now, let&#8217;s create a method to call our <code>ToQueryStringUsingNewtonsoftJson()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string CreateURLWithBookAsQueryParamsUsingNewtonsoftJson(string url, Book book)\r\n{\r\n    var queryParams = ToQueryStringUsingNewtonsoftJson(book);\r\n\r\n    return $\"{url}?{queryParams}\";\r\n}<\/pre>\n<p>Once again we define a method that accepts <code>url<\/code> and <code>book<\/code> object as the input parameters. Then, we invoke the <code>ToQueryStringUsingNewtonsoftJson()<\/code> method to build the <code>queryParams<\/code>. Finally, we concatenate the <code>url<\/code> and <code>queryParams<\/code> to form the complete URL.<\/p>\n<p>Let&#8217;s call the method:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine(QueryStringSerializer.CreateURLWithBookAsQueryParamsUsingNewtonsoftJson(BaseApiUrl, new Book()));<\/code><\/p>\n<p>We invoke the <code>CreateURLWithBookAsQueryParamsUsingNewtonsoftJson()<\/code>\u00a0method to build the complete URL.<\/p>\n<p>Let&#8217;s inspect the complete URL:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">https:\/\/test.com?Author=George+Orwell&amp;Language=English<\/code><\/p>\n<h2><a id=\"dealing-with-nested-objects-during-serialization\"><\/a>Dealing With Nested Objects During Serialization<\/h2>\n<p>When dealing with complex data structures in C# object serialization, one common scenario is handling nested objects.<\/p>\n<p>Nested objects occur when an object contains properties that are themselves objects. Maintaining the structure and relationships within the data is crucial, and ensuring proper serialization of these nested objects is essential.<\/p>\n<p>First, let&#8217;s create three model classes, <code>Distributor<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Distributor\r\n{\r\n    public string Name { get; set; } = \"TechDistributors\";\r\n}<\/pre>\n<p>Then, <code>Manufacturer<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Manufacturer\r\n{\r\n    public string Location { get; set; } = \"Silicon Valley\";\r\n    public Distributor Distributor { get; set; } = new Distributor();\r\n}<\/pre>\n<p>We include the <code>Distributor<\/code> class property as a nested object in the <code>Manufacturer<\/code> class.<\/p>\n<p>Finally, <code>Product<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Product\r\n{\r\n    public string Name { get; set; } = \"Laptop\";\r\n    public string Category { get; set; } = \"Electronics\";\r\n    public Manufacturer Manufacturer { get; set; } = new Manufacturer();\r\n}<\/pre>\n<p>Here, we will include the <code>Manufacturer<\/code> class property as a nested object in the <code>Product<\/code> class.<\/p>\n<p>We&#8217;ll start by defining a method to get the nested property values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static IEnumerable&lt;string&gt; GetNestedPropertyValues(object obj)\r\n{\r\n    return obj.GetType().GetProperties()\r\n        .SelectMany(nestedProperty =&gt; GetPropertyValues(nestedProperty, obj));\r\n}<\/pre>\n<p>Here, we define a <code>GetNestedPropertyValues()<\/code> method that takes <code>object<\/code> type as a parameter.<\/p>\n<p>As a first step, we get the runtime type of the object <code>obj<\/code> and retrieve an array of <code>PropertyInfo<\/code>. Then, we apply <code>SelectMany<\/code> LINQ function to flatten the nested properties into a single sequence. We accomplish this by calling our <code>GetPropertyValues()<\/code> method.\u00a0<\/p>\n<p>Next, we need to define <code>GetPropertyValue()<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static IEnumerable&lt;string&gt; GetPropertyValues(PropertyInfo property, object parentObject)\r\n{\r\n    string propertyName = property.Name;\r\n    object propertyValue = property.GetValue(parentObject)!;\r\n\r\n    if (property.PropertyType.IsClass &amp;&amp; property.PropertyType != typeof(string))\r\n    {\r\n\r\n        return GetNestedPropertyValues(propertyValue)\r\n            .Select(nestedValue =&gt;\r\n                $\"{HttpUtility.UrlEncode(propertyName)}.{nestedValue}\");\r\n    }\r\n    else\r\n    {\r\n        return new[] { $\"{HttpUtility.UrlEncode(propertyName)}={HttpUtility.UrlEncode(propertyValue.ToString())}\" };\r\n    }\r\n}<\/pre>\n<p>Here, we define a <code>GetPropertyValues()<\/code> method that accepts <code>object<\/code> type and <code>PropertyInfo<\/code> as the input parameters.\u00a0 Next, we extract the property name and value, checking if the property is a class and not a string.<\/p>\n<p>If the property is a nested object (i.e. a class and not a string), we recursively call our <code>GetNestedPropertyValues()<\/code> method to handle the nested properties. Then, we prefix the property name with the parent property name to maintain the hierarchy.\u00a0<\/p>\n<p>In the case where the property is not a nested object, we return a single-element array with a URL-encoded string representation of the property&#8217;s name and value.<\/p>\n<p>Now, let&#8217;s create a new method to call the <code>GetNestedPropertyValues()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string NestedObjectToQueryString(Product product)\r\n{\r\n    var propValues = GetNestedPropertyValues(product);\r\n    return string.Join('&amp;', propValues);\r\n}<\/pre>\n<p>Here, we define our <code>NestedObjectToQueryString()<\/code> method that accepts a <code>product<\/code> object as the input parameter.<\/p>\n<p>First, we call the <code>GetNestedPropertyValues()<\/code>\u00a0method passing the <code>product<\/code> object. Finally, we use the <code>string.Join()<\/code> method to concatenate the <code>propValues<\/code>.<\/p>\n<p>So, let&#8217;s proceed to invoke the method to build the complete URL:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string CreateURLWithProductAsQueryParams(string url, Product product)\r\n{\r\n    var queryParams = NestedObjectToQueryString(product);\r\n\r\n    return $\"{url}?{queryParams}\";\r\n}<\/pre>\n<p>In this block, we define a <code>CreateURLWithProductAsQueryParams()<\/code> method that invokes our <code>NestedObjectToQueryString()<\/code>\u00a0method to obtain the <code>queryParams<\/code>\u00a0and return the full URL.<\/p>\n<p>Let&#8217;s see it in action:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine(QueryStringSerializer.CreateURLWithProductAsQueryParams(BaseApiUrl, new Product()));<\/code><\/p>\n<p>Let&#8217;s see the output:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">https:\/\/test.com?Name=Laptop&amp;Category=Electronics&amp;Manufacturer.Location=Silicon+Valley&amp;Manufacturer.Distributor.Name=TechDistributors<\/code><\/p>\n<p>Here, <code>Manufacturer.Location<\/code>\u00a0indicates that the <code>Location<\/code> property is nested within the <code>Manufacturer<\/code> property. Similarly, <code>Manufacturer.Distributor.Name<\/code> indicates that the <code>Name<\/code> property of the <code>Distributor<\/code> object is nested within the <code>Manufacturer<\/code> property.\u00a0<\/p>\n<h2><a id=\"how-to-handle-arrays-nested-objects-during-serialization\"><\/a>How to Handle Arrays and Nested Objects During Serialization<\/h2>\n<p>Serializing arrays and collections introduces unique challenges that require careful consideration.<\/p>\n<p><strong>Unlike single values or simple objects, arrays and collections can contain multiple elements, and appropriately serializing each element becomes necessary.<\/strong><\/p>\n<p>Let&#8217;s proceed to create two model classes, <code>Address<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Address\r\n{\r\n    public string Country { get; set; } = \"Australia\";\r\n}<\/pre>\n<p>And <code>Person<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Person\r\n{\r\n    public string FirstName { get; set; } = \"Smith\";\r\n    public int Age { get; set; } = 25;\r\n    public string[] Hobbies { get; set; } = { \"Reading\", \"Traveling\", \"Gaming\" };\r\n    public Address Address { get; set; } = new Address();\r\n}<\/pre>\n<p>Here, we initialize the <code>Hobbies<\/code> properties as a string array and include the <code>Address<\/code> class property as a nested object in the <code>Person<\/code> class.<\/p>\n<p>Let&#8217;s create a method to get the array values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static IEnumerable&lt;string&gt; GetArrayValues(string propertyName, Array array)\r\n{\r\n    return Enumerable.Range(0, array.Length)\r\n        .Select(i =&gt;\r\n        {\r\n            var arrayElementValue = HttpUtility.UrlEncode(array.GetValue(i)?.ToString()) ?? string.Empty;\r\n            var arrayPropName = propertyName + $\"[{i}]\";\r\n            return $\"{HttpUtility.UrlEncode(arrayPropName)}={arrayElementValue}\";\r\n        });\r\n}<\/pre>\n<p>We define a <code>GetArrayValues()<\/code> method that accepts <code>propertyName<\/code> and <code>array<\/code> as the input parameter.<\/p>\n<p>Then, using <code>Enumerable.Range<\/code> to create a sequence of indices, we generate key-value pairs for each array element by combining the property name with the index enclosed within square brackets: <code>MyPropertyName[i]<\/code>. We then URL-encode this key value along with the array elements value to form our key-value pair. <strong>It is important to note that according to<\/strong> <a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc3986#appendix-A\" target=\"_blank\" rel=\"nofollow noopener\">Appendix A of RFC 3986<\/a>, <strong>we need to be sure to URL-encode both<\/strong> <code>propertyName<\/code> <strong>and the square brackets in our query string.<\/strong><\/p>\n<p>If an array element happens to be <code>null<\/code>, the resulting string in the query parameter could appear as &#8220;MyPropertyName[i]=&#8221;. Although technically valid, it may lead to unexpected results when the query string is parsed.<\/p>\n<p>Now, let&#8217;s update our existing <code>GetPropertyValues()<\/code> method to also deal with arrays:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8-11\">private static IEnumerable&lt;string&gt; GetPropertyValues(PropertyInfo property, object parentObject)\r\n{\r\n    string propertyName = property.Name;\r\n    object propertyValue = property.GetValue(parentObject)!;\r\n\r\n    if (property.PropertyType.IsClass &amp;&amp; property.PropertyType != typeof(string))\r\n    {\r\n        if (property.PropertyType.IsArray)\r\n        {\r\n            return GetArrayValues(propertyName, (Array)propertyValue);\r\n        }\r\n        else\r\n        {\r\n            return GetNestedPropertyValues(propertyValue)\r\n                .Select(nestedValue =&gt;\r\n                    $\"{HttpUtility.UrlEncode(propertyName)}.{HttpUtility.UrlEncode(nestedValue)}\");\r\n        }\r\n    }\r\n    else\r\n    {\r\n        return new[] { $\"{HttpUtility.UrlEncode(propertyName)}={HttpUtility.UrlEncode(propertyValue.ToString())}\" };\r\n    }\r\n}<\/pre>\n<p>Here, we have added a check for array properties which calls the corresponding <code>GetArrayValues()<\/code> method passing the property name and the property value cast as an array.<\/p>\n<p>Now, let&#8217;s define a new method to exercise our array serializer:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static string ObjectWithArrayAndNestedObjectToQueryString(Person person)\r\n{\r\n    var propValues = GetNestedPropertyValues(person);\r\n\r\n    var finalQueryString = string.Join('&amp;', propValues);\r\n\r\n    return finalQueryString;\r\n}<\/pre>\n<p>Our new method takes a <code>Person<\/code> object and subsequently invokes the existing <code>GetNestedPropertyValues()<\/code> method to obtain the <code>propValues<\/code> to build the final query string. Once again our final step invokes <code>string.Join()<\/code> to form the <code>finalQueryString<\/code>.<\/p>\n<p>Let&#8217;s create another method to invoke the <code>ObjectWithArrayToQueryString()<\/code>\u00a0method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static string CreateURLWithPersonAsQueryParams(string url, Person person)\r\n{\r\n    var queryParams = ObjectWithArrayToQueryString(person);\r\n\r\n    return $\"{url}?{queryParams}\";\r\n}<\/pre>\n<p>Our new <code>CreateURLWithPersonAsQueryParams()<\/code> method accepts a <code>url<\/code> and a <code>person<\/code> object as the input parameters. Inside the method we call <code>ObjectWithArrayToQueryString()<\/code> to build the <code>queryParams<\/code>, and finally, combine that with our base URL and return the whole string.<\/p>\n<p>So, let&#8217;s proceed to call the method:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine(QueryStringSerializer.CreateURLWithPersonAsQueryParams(BaseApiUrl, new Person()));<\/code><\/p>\n<p>Let&#8217;s invoke the <code>CreateURLWithPersonAsQueryParams()<\/code>\u00a0method to frame the complete URL.<\/p>\n<p>Let&#8217;s inspect the final URL:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">https:\/\/test.com?FirstName=Smith&amp;Age=25&amp;Hobbies%5b0%5d=Reading&amp;Hobbies%5b1%5d=Traveling&amp;Hobbies%5b2%5d=Gaming&amp;Address.Country=Australia<\/code><\/p>\n<p>Here, the use of square brackets (URL-encoded as <code>%5b<\/code> and <code>%5d<\/code> respectively) and an index indicates that the values belong to the elements of an array in the <code>Person<\/code> class and <code>Address.Country<\/code> indicates that the <code>Country<\/code> property is nested within the <code>Address<\/code> property.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we have seen how to serialize an object into query string format using reflection and the third-party library <code>Newtonsoft.Json<\/code>. We also learned how to deal with nested objects and arrays during serialization.\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn how to serialize an object into query string format using C#. We will discuss the challenges we face when dealing with nested objects and arrays and how to deal with them. Serialization is a crucial concept in programming, particularly in C#. It involves converting the state of an object [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[1811,819,47,130,45],"class_list":["post-103713","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-c","tag-query-string","tag-rest-api","tag-web-api","tag-web-development","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Serialize an Object into Query String Format in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Serialize an Object into Query String Format in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-12-24T09:23:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-01-09T14:02:45+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Serialize an Object into Query String Format in C#\",\"datePublished\":\"2023-12-24T09:23:10+00:00\",\"dateModified\":\"2024-01-09T14:02:45+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\"},\"wordCount\":1441,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"C#\",\"Query String\",\"REST API\",\"Web API\",\"web development\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\",\"url\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\",\"name\":\"How to Serialize an Object into Query String Format in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-12-24T09:23:10+00:00\",\"dateModified\":\"2024-01-09T14:02:45+00:00\",\"description\":\"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Serialize an Object into Query String Format in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Serialize an Object into Query String Format in C# - Code Maze","description":"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/","og_locale":"en_US","og_type":"article","og_title":"How to Serialize an Object into Query String Format in C# - Code Maze","og_description":"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects","og_url":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/","og_site_name":"Code Maze","article_published_time":"2023-12-24T09:23:10+00:00","article_modified_time":"2024-01-09T14:02:45+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Serialize an Object into Query String Format in C#","datePublished":"2023-12-24T09:23:10+00:00","dateModified":"2024-01-09T14:02:45+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/"},"wordCount":1441,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["C#","Query String","REST API","Web API","web development"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/","url":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/","name":"How to Serialize an Object into Query String Format in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-12-24T09:23:10+00:00","dateModified":"2024-01-09T14:02:45+00:00","description":"In this article, we will learn how to serialize an object into query string format using C# and how to deal with nested objects","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-serialize-object-into-query-string\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Serialize an Object into Query String Format in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103713","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=103713"}],"version-history":[{"count":4,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103713\/revisions"}],"predecessor-version":[{"id":103986,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103713\/revisions\/103986"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=103713"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=103713"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=103713"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}