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!

0

3 Answers 3

32

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])
           );
Sign up to request clarification or add additional context in comments.

8 Comments

How do you handle arrays?
The resultset of your answer does not match the OP's requested resultset.
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" }
@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 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
|
7

It also possible to use

var collection = HttpUtility.ParseQueryString(query);
Newtonsoft.Json.JsonConvert.SerializeObject(collection.AllKeys.ToDictionary(y => y, y => collection[y]));

Comments

-3

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

1 Comment

OP is asking for a server side solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.