4

C#でクエリ文字列をJSONにシリアル化しようとしています。期待した結果が得られず、誰かが説明してくれることを期待しています。クエリ「name」のみを取得し、「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"]

後者のサンプル出力に似た文字列を取得する方法を知っている人はいますか?私も試しました

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

NewtonsoftJsonと同じ結果が得られました。

編集-以下の答えに基づいた最終的な作業コードは次のとおりです。

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

2 に答える 2

4

さて、クエリ文字列はNameValueCollectionであり、NameValueCollectionをシリアル化する方法はここにあります:NameValueCollectionをJSON文字列に変換する方法は?

于 2011-09-19T14:17:28.037 に答える
4

Dictionary<string,string>これは、JavaScriptSerializer または Newtonsoft の Json.Net によって容易にシリアライズできる に評価されます。

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

繰り返されるキーはすべてRequest.QueryString、ディクショナリ内の単一のキーになり、その値はコンマで区切られて連結されます。

もちろん、これNameValueCollectionは だけでなく、任意の にも機能しますRequest.QueryString

于 2013-11-20T18:43:14.327 に答える