What Are Some Options To Convert Url-Encoded Form Data to JSON in .Net What Are Some Options To Convert Url-Encoded Form Data to JSON in .Net json json

What Are Some Options To Convert Url-Encoded Form Data to JSON in .Net


I've written a utility class for parsing query strings and form data. It's available at:

https://gist.github.com/peteroupc/5619864

Example:

// Example query string from the questionString test="Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d";// Convert the query string to a JSON-friendly dictionaryvar o=QueryStringHelper.QueryStringToDict(test);// Convert the dictionary to a JSON string using the JSON.NET// library <http://json.codeplex.com/>var json=JsonConvert.SerializeObject(o);// Output the JSON string to the consoleConsole.WriteLine(json);

Let me know if it works for you.


The .NET Framework 4.5 includes everything you need to convert url-encoded form data to JSON. In order to do this you have to add a reference to the namespace System.Web.Extension in your C# project. After that you can use the JavaScriptSerializer class which provides you with everything you need to do the conversion.

The Code

using System.Web;using System.Web.Script.Serialization;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            var dict = HttpUtility.ParseQueryString("Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d");            var json = new JavaScriptSerializer().Serialize(                                                     dict.Keys.Cast<string>()                                                         .ToDictionary(k => k, k => dict[k]));            Console.WriteLine(json);            Console.ReadLine();        }    }}

The Output

{    "Property1":"A",    "Property2":"B",    "Property3[0][SubProperty1]":"a",    "Property3[0][SubProperty2]":"b",    "Property3[1][SubProperty1]":"c",    "Property3[1][SubProperty2]":"d"}

Notice: The output does not contain linebreaks or any formatting

Source: How do I convert a querystring to a json string?