17

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!

Robert
  • 2,745
  • 3
  • 17
  • 16

3 Answers3

31

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])
           );
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 2
    How do you handle arrays? – Arman Bimatov Mar 31 '14 at 04:11
  • The resultset of your answer does not match the OP's requested resultset. – Rafael Herscovici Nov 05 '14 at 15:14
  • @Dementic It exactly produces the json string OP wants... (BTW: See the green tick at the left :) ) – L.B Nov 05 '14 at 17:29
  • 1
    Accepted answer dosent mean that it does exactly what was asked. the result of your code would be something like `{ "key": "keyName", "val": "value"}` while the OP asked for `{ "keyName": " value" }` – Rafael Herscovici Nov 06 '14 at 08:10
  • 3
    @Dementic `the result of your code would be ......`, **NO**, What is so hard to understand, I just rerun above code and got `{"ID":"951357852456","FNAME":"Jaime","LNAME":"Lopez"}`. Next time please make sure if you don't want to downvote a correct answer. – L.B Nov 06 '14 at 17:41
  • I have to agree with @L.B - I ran the code and it works as expected – Adam Davis Oct 12 '18 at 14:13
  • 1
    @L.B This answer is not precise, it will not work if in the query string there is an array. Maybe it's accepptable but is better if the answer specify this limitation – Skary Mar 06 '22 at 16:27
7

It also possible to use

var collection = HttpUtility.ParseQueryString(query);
Newtonsoft.Json.JsonConvert.SerializeObject(collection.AllKeys.ToDictionary(y => y, y => collection[y]));
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
-3

You can use jQuery to do this: jQuery.Param.

JSK NS
  • 3,346
  • 2
  • 25
  • 42