如何将json转换为NameValueCollection

问题描述 投票:5回答:3

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

c# .net json
3个回答
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可以工作。但是,我尚未验证它是否确实如此。


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


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