2011-09-19 5 views
4

C#에서 JSON에 대한 쿼리 문자열을 직렬화하려고합니다. 예상 한 결과를 얻지 못하고 누군가가 설명하기를 희망합니다. 나는 단지 "값"이 아닌 "이름"이라는 쿼리 만 얻는 몇 가지 이유가 있습니다.C#에서 Json으로 쿼리 문자열을 serialize합니다. 값이 나타나지 않고 키만 표시됩니다. 왜?

//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; 
     } 
    } 
} 

답변

4

글쎄, 쿼리 문자열을 NameValueCollection은, 어떻게 NameValueCollection은 직렬화하는 방법이다가 여기에 있습니다 : :

편집 - 다음은 아래의 답변에 따라 최종 작업 코드입니다 이것은 Dictionary<string,string>로 평가 how to convert NameValueCollection to JSON string?

+0

@ giedrius- 감사합니다. 이제 작동합니다. 쿼리 문자열을 JSON으로 변환하는 데 직접적인 접근 방식이 없다는 것이 이상한 것처럼 보입니다.하지만이 솔루션은 상당히 간단합니다. –

4

하는에

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

모든 반복 키 : JavaScriptSerializer 또는 Newtonsoft의 Json.Net이 쉽게 직렬화은 딕셔너리의 단일 키로 끝나며 그 값은 함께 쉼표로 구분하여 연결됩니다.

물론 Request.QueryString이 아닌 NameValueCollection에 대해서도 작동합니다.