4

I'm trying to serialize a querystring to JSON in C#. I'm not getting the results I expected, and am hoping someone can explain. Some reason I'm only getting the query "name" and not the "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"]

Anyone know how to get a string resembling the latter sample output? I've also tried

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

and gotten identical results as the Newtonsoft Json.

EDIT- Here's the final 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;
        }
    }
}
Hairgami_Master
  • 5,429
  • 10
  • 45
  • 66

2 Answers2

4

This evaluates to a Dictionary<string,string> which is readily serializable by JavaScriptSerializer or Newtonsoft's Json.Net:

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

Any repeated keys in Request.QueryString end up as a single key in the dictionary, whose values are concatenated together separated by commas.

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

Matt
  • 20,108
  • 1
  • 57
  • 70
4

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

Community
  • 1
  • 1
Giedrius
  • 8,430
  • 6
  • 50
  • 91
  • @giedrius- Thanks! Works now. Seems strange there isn't a more direct approach to converting a query string to JSON, but that solution is fairly simple. – Hairgami_Master Sep 19 '11 at 14:21