[json] ASP.NET에서 JSON을 간단한 Dictionary <string, string>으로 직렬화 해제하려면 어떻게해야합니까?

POST를 통해 ASP.NET으로 다시 전송되는 JSON의 간단한 키 / 값 목록이 있습니다. 예:

{ "key1": "value1", "key2": "value2"}

강력한 형식의 .NET 개체로 역 직렬화하려고하지 않습니다.

나는 보통 오래된 Dictionary (Of String, String) 또는 그와 동등한 (해시 테이블, Dictionary (Of String, Object), 구식 StringDictionary가 필요합니다 .2 차원 문자열 배열이 저에게 효과적입니다.

ASP.NET 3.5에서 사용 가능한 모든 항목과 널리 사용되는 Json.NET (이미 클라이언트 의 직렬화 에 사용 하고 있음)을 사용할 수 있습니다.

분명히 이러한 JSON 라이브러리 중 어느 것도 이마를 뛰어 넘는 명백한 기능을 가지고 있지 않습니다. 강력한 계약을 통한 리플렉션 기반 역 직렬화에 전적으로 집중되어 있습니다.

어떤 아이디어?

한계 :

  1. 내 JSON 파서를 구현하고 싶지 않습니다.
  2. 아직 ASP.NET 4.0을 사용할 수 없습니다
  3. 더 이상 사용되지 않는 오래된 ASP.NET 클래스에서 JSON을 사용하지 않는 것이 좋습니다.


답변

Json.NET 이 이것을 수행합니다 …

string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

더 많은 예제 : Json.NET으로 컬렉션 직렬화


답변

.NET에는 3.5 어셈블리 의 Dictionary<String, Object>비아 System.Web.Script.Serialization.JavaScriptSerializer유형 으로 JSON 문자열을 캐스트하는 방법이 내장되어 있음을 발견했습니다 System.Web.Extensions. 방법을 사용하십시오 DeserializeObject(String).

정적 .net 페이지 메소드에 컨텐츠 유형 ‘application / json’의 아약스 게시 (jquery를 통해)를 수행 할 때이 문제가 발생하여 유형 (단일 매개 변수가있는) 메소드 Object가이 사전을 마술처럼 받았다는 것을 알았습니다 .


답변

인터넷을 검색하고이 게시물에 걸려 넘어지는 사람들을 위해 JavaScriptSerializer 클래스 사용 방법에 대한 블로그 게시물을 작성했습니다.

더 읽기 …
http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/

예를 들면 다음과 같습니다.

var json = "{\"id\":\"13\", \"value\": true}";
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(json);
Console.WriteLine(table["id"]);
Console.WriteLine(table["value"]);


답변

외부 JSON 구현을 사용하지 않으려 고 다음과 같이 역 직렬화했습니다.

string json = "{\"id\":\"13\", \"value\": true}";

var serializer = new JavaScriptSerializer(); //using System.Web.Script.Serialization;

Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json);


답변

나는 같은 문제가 있었으므로 이것을 내 자신을 썼다. 이 솔루션은 여러 수준으로 역 직렬화 할 수 있으므로 다른 답변과 차별화됩니다.

JSON 문자열을 deserializeToDictionary 함수로 보내면 강력하게 형식화되지 않은 Dictionary<string, object>객체 가 반환됩니다 .

이전 코드

private Dictionary<string, object> deserializeToDictionary(string jo)
{
    var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
    var values2 = new Dictionary<string, object>();
    foreach (KeyValuePair<string, object> d in values)
    {
        // if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
        if (d.Value is JObject)
        {
            values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
        }
        else
        {
            values2.Add(d.Key, d.Value);
        }
    }
    return values2;
}

예 : Dictionary<string, object>Facebook JSON 응답의 객체를 반환 합니다.

테스트

private void button1_Click(object sender, EventArgs e)
{
    string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\",  hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
    Dictionary<string, object> values = deserializeToDictionary(responsestring);
}

참고 : 고향은 Dictionary<string, object>
개체 로 더 deserilize .

최신 정보

JSON 문자열에 배열이 없으면 이전 답변이 효과적입니다. 이것은 List<object>요소가 배열 인 경우 추가로 직렬화 해제 합니다.

JSON 문자열을 deserializeToDictionaryOrList 함수로 보내면 강력하게 형식화되지 않은 Dictionary<string, object>객체 또는을 반환 합니다 List<object>.

private static object deserializeToDictionaryOrList(string jo,bool isArray=false)
{
    if (!isArray)
    {
        isArray = jo.Substring(0, 1) == "[";
    }
    if (!isArray)
    {
        var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
        var values2 = new Dictionary<string, object>();
        foreach (KeyValuePair<string, object> d in values)
        {
            if (d.Value is JObject)
            {
                values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
            }
            else if (d.Value is JArray)
            {
                values2.Add(d.Key, deserializeToDictionary(d.Value.ToString(), true));
            }
            else
            {
                values2.Add(d.Key, d.Value);
            }
        }
        return values2;
    }else
    {
        var values = JsonConvert.DeserializeObject<List<object>>(jo);
        var values2 = new List<object>();
        foreach (var d in values)
        {
            if (d is JObject)
            {
                values2.Add(deserializeToDictionary(d.ToString()));
            }
            else if (d is JArray)
            {
                values2.Add(deserializeToDictionary(d.ToString(), true));
            }
            else
            {
                values2.Add(d);
            }
        }
        return values2;
    }
}


답변

가볍고 추가되지 않은 참조 유형의 접근 방식을 사용하는 경우 방금 작성한이 코드가 작동합니다 (100 % 견고성을 보장 할 수는 없습니다).

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

public Dictionary<string, object> ParseJSON(string json)
{
    int end;
    return ParseJSON(json, 0, out end);
}
private Dictionary<string, object> ParseJSON(string json, int start, out int end)
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    bool escbegin = false;
    bool escend = false;
    bool inquotes = false;
    string key = null;
    int cend;
    StringBuilder sb = new StringBuilder();
    Dictionary<string, object> child = null;
    List<object> arraylist = null;
    Regex regex = new Regex(@"\\u([0-9a-z]{4})", RegexOptions.IgnoreCase);
    int autoKey = 0;
    for (int i = start; i < json.Length; i++)
    {
        char c = json[i];
        if (c == '\\') escbegin = !escbegin;
        if (!escbegin)
        {
            if (c == '"')
            {
                inquotes = !inquotes;
                if (!inquotes && arraylist != null)
                {
                    arraylist.Add(DecodeString(regex, sb.ToString()));
                    sb.Length = 0;
                }
                continue;
            }
            if (!inquotes)
            {
                switch (c)
                {
                    case '{':
                        if (i != start)
                        {
                            child = ParseJSON(json, i, out cend);
                            if (arraylist != null) arraylist.Add(child);
                            else
                            {
                                dict.Add(key, child);
                                key = null;
                            }
                            i = cend;
                        }
                        continue;
                    case '}':
                        end = i;
                        if (key != null)
                        {
                            if (arraylist != null) dict.Add(key, arraylist);
                            else dict.Add(key, DecodeString(regex, sb.ToString()));
                        }
                        return dict;
                    case '[':
                        arraylist = new List<object>();
                        continue;
                    case ']':
                        if (key == null)
                        {
                            key = "array" + autoKey.ToString();
                            autoKey++;
                        }
                        if (arraylist != null && sb.Length > 0)
                        {
                            arraylist.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        dict.Add(key, arraylist);
                        arraylist = null;
                        key = null;
                        continue;
                    case ',':
                        if (arraylist == null && key != null)
                        {
                            dict.Add(key, DecodeString(regex, sb.ToString()));
                            key = null;
                            sb.Length = 0;
                        }
                        if (arraylist != null && sb.Length > 0)
                        {
                            arraylist.Add(sb.ToString());
                            sb.Length = 0;
                        }
                       continue;
                    case ':':
                        key = DecodeString(regex, sb.ToString());
                        sb.Length = 0;
                        continue;
                }
            }
        }
        sb.Append(c);
        if (escend) escbegin = false;
        if (escbegin) escend = true;
        else escend = false;
    }
    end = json.Length - 1;
    return dict; //theoretically shouldn't ever get here
}
private string DecodeString(Regex regex, string str)
{
    return Regex.Unescape(regex.Replace(str, match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber))));
}

[이것이 OP 제한 # 1을 위반한다는 것을 알고 있지만 기술적으로는 작성하지 않았습니다.]


답변

방금 중첩 된 사전 을 구문 분석해야했습니다.

{
    "x": {
        "a": 1,
        "b": 2,
        "c": 3
    }
}

JsonConvert.DeserializeObject도움이되지 않는 곳 . 나는 다음과 같은 접근법을 발견했다.

var dict = JObject.Parse(json).SelectToken("x").ToObject<Dictionary<string, int>>();

SelectToken당신이 원하는 분야에 파고 있습니다. "x.y.z"JSON 객체로 더 나아가는 경로를 지정할 수도 있습니다 .