Serialize querystring as Json in C # - values ​​are not displayed, only keys. What for?

I am trying to serialize a JSON request in C #. I do not get the expected results, and I hope someone can explain. For some reason, I get the request "name" rather than "value".

//Sample Query: http://www.mydomain.com/Handler.ashx?method=preview&appid=1234 //Generic handler code: public void ProcessRequest(HttpContext context) { string json = JsonConvert.SerializeObject(context.Request.QueryString); context.Response.ContentType = "text/plain"; context.Response.Write(json); } //Returns something like this: ["method", "appid"] //I would expect to get something like this: ["method":"preview", "appid":"1234"] 

Does anyone know how to get a string similar to the last sample output? I also tried

 string json = new JavaScriptSerializer().Serialize(context.Request.QueryString); 

and got identical results like Newtonsoft Json.

EDIT. Here is the working code based on the answer below:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using Newtonsoft.Json; using System.Collections.Specialized; namespace MotoAPI3 { public class Json : IHttpHandler { public void ProcessRequest(HttpContext context) { var dict = new Dictionary<string, string>(); foreach (string key in context.Request.QueryString.Keys) { dict.Add(key, context.Request.QueryString[key]); } string json = new JavaScriptSerializer().Serialize(dict); context.Response.ContentType = "text/plain"; context.Response.Write(json); } public bool IsReusable { get { return false; } } } 
+4
source share
2 answers

Well, the query string is NameValueCollection, and how to serialize NameValueCollection here: how to convert NameValueCollection to JSON string?

+4
source

This is evaluated as a Dictionary<string,string> , which is easily serialized by JavaScriptSerializer or Newtonsoft Json.Net:

 Request.QueryString.AllKeys.ToDictionary(k => k, k => Request.QueryString[k]) 

Any duplicate keys in Request.QueryString end as a single key in a dictionary whose values ​​are combined together with a comma.

Of course, this also works for any NameValueCollection , not just Request.QueryString .

+4
source

All Articles