如何将json转换为NameValueCollection

时间:2012-07-09 16:03:31

标签: c# .net json

如何简单地将一串JSON转换为C#NameValueCollection,最好不使用第三方解析器?

3 个答案:

答案 0 :(得分:10)

我不确定为什么每个人仍然建议使用JSON.NET来反序列化JSON。我写了blog post on how to deserialize JSON to C#

简而言之,就是这样:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>(jsonText);

NameValueCollection nvc = null;
if (dict != null) {
  nvc = new NameValueCollection(dict.Count);
  foreach (var k in dict) {
    nvc.Add(k.Key, k.Value);
  }
}
                    }
var json = jss.Serialize(dict);
Console.WriteLine(json);

请务必添加对System.Web.Extensions.dll的引用。

注意: 我通常反序列化为dynamic,所以我假设NameValueCollection可以正常工作。但是,我还没有确认它是否确实存在。

答案 1 :(得分:3)

修改

没有第三方开发的纯.net解决方案看起来像JavaScriptSerializer – Dictionary to JSON Serialization and Deserialization


使用Json.NET

string jsonstring = @"{""keyabc"":""valueabc"",""keyxyz"":""valuexyz""}";

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

检查@jon回答建议相同:.Net Linq to JSON with Newtonsoft JSON library

答案 2 :(得分:0)

如果您的JSON包含嵌套对象,则下面的解决方案将正确处理它们(基于JSON.NET,但是您可以适应所选的JSON解析器)。

此用法示例:

var json = "{\"status\":\"paid\",\"date\":\"2019-10-09T17:30:51.479Z\",\"customer\":{\"id\":123456789,\"country\":\"br\",\"name\":\"Thomas Vilhena\",\"phone_numbers\":[\"+5511987654321\"],\"documents\":[{\"id\":\"doc_id\"}]}}";

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);            
var nvc = new NameValueCollection(dict.Count);
AddKeyValuePairs(nvc, dict);

Console.WriteLine(nvc["status"]);
Console.WriteLine(nvc["date"]);
Console.WriteLine(nvc["customer[phone_numbers][0]"]);
Console.WriteLine(nvc["customer[id]"]);
Console.WriteLine(nvc["customer[documents][0][id]"]);

产生以下输出:

paid
09.10.2019 17:30
+5511987654321
123456789
doc_id

这是实现:

private static void AddKeyValuePairs(
    NameValueCollection nvc,
    Dictionary<string, object> dict,
    string prefix = null)
{
    foreach (var k in dict)
    {
        var key = prefix == null ? k.Key : prefix + "[" + k.Key + "]";
        if (k.Value != null)
            AddKeyValuePair(nvc, key, k.Value);
    }
}

private static void AddKeyValuePair(
    NameValueCollection nvc,
    string key,
    object value)
{
    if (value is string || value.GetType().IsPrimitive)
    {
        nvc.Add(key, value.ToString());
    }
    else if (value is DateTime)
    {
        nvc.Add(key, ((DateTime)value).ToString("g"));
    }
    else
    {
        AddNonPrimitiveValue(nvc, key, value);
    }
}

private static void AddNonPrimitiveValue(
    NameValueCollection nvc,
    string key,
    object value)
{
    var a = value as JArray;
    if (a != null)
    {
        for (int i = 0; i < a.Count; i++)
            AddKeyValuePair(nvc, key + "[" + i + "]", a[i]);
    }
    else
    {
        var v = value as JValue;
        if (v != null)
        {
            AddKeyValuePair(nvc, key, v.Value);
        }
        else
        {
            var j = value as JObject;
            if (j != null)
                AddKeyValuePairs(nvc, j.ToObject<Dictionary<string, object>>(), key);
        }
    }
}