我正在尝试在 C# 中将查询字符串序列化为 JSON。我没有得到我预期的结果,希望有人能解释一下。出于某种原因,我只得到查询“名称”而不是“值”。
//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"]
任何人都知道如何获得类似于后一个示例输出的字符串?我也试过
string json = new JavaScriptSerializer().Serialize(context.Request.QueryString);
并得到与 Newtonsoft Json 相同的结果。
编辑-这是基于以下答案的最终工作代码:
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;
}
}
}