Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a web request that is sending the server data that is in the format application/x-www-form-urlencoded. I would like to convert it to application/json.

Example:

URL-encoded form data:

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 

Pretty version:

Property1=A Property2=B Property3[0][SubProperty1]=a Property3[0][SubProperty2]=b Property3[1][SubProperty1]=c Property3[1][SubProperty2]=d 

The above data needs to be converted to the following JSON data:

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

Question:

Are there any free tools that are capable of doing this? I have not been able to find any myself and if they exist, I'd rather consume them than writing one myself, but if it comes to that, I will.

A C#/.Net solution is preferred.

like image 242
Dan Avatar asked May 14 '13 20:05

Dan


People also ask

How to get data in JSON form?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

How to pass JSON object in FormData?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

How to get form data in JSON format using jQuery?

var obj = $('form'). serializeJSON(); var jsonString = JSON. stringify(obj);


1 Answers

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 question String 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 dictionary var 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 console Console.WriteLine(json); 

Let me know if it works for you.

like image 78
Peter O. Avatar answered Sep 28 '22 21:09

Peter O.