Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a querystring to a json string?

Tags:

json

c#

.net

Using server-side C#, how can I convert a querystring to a JSON string of keys and values? For example, I want to convert

"ID=951357852456&FNAME=Jaime&LNAME=Lopez"

to

{ "ID":"951357852456" , "FNAME":"Jaime" , "LNAME":"Lopez" }

I know how to manually parse and format but, before starting down that road, I thought I'd ask since there might be a library that does it better. Thanks!

like image 931
Robert Avatar asked Sep 14 '12 17:09

Robert


People also ask

Can we convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


2 Answers

This gives the exactly same json you want

var dict = HttpUtility.ParseQueryString("ID=951357852456&FNAME=Jaime&LNAME=Lopez");
var json = new JavaScriptSerializer().Serialize(
                    dict.AllKeys.ToDictionary(k => k, k => dict[k])
           );
like image 171
L.B Avatar answered Oct 10 '22 06:10

L.B


It also possible to use

var collection = HttpUtility.ParseQueryString(query);
Newtonsoft.Json.JsonConvert.SerializeObject(collection.AllKeys.ToDictionary(y => y, y => collection[y]));
like image 7
Bastien Vandamme Avatar answered Oct 10 '22 08:10

Bastien Vandamme