如何将json转换为NameValueCollection

Jam*_*mes 5 .net c# json

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

JP *_*son 10

我不确定为什么每个人仍然推荐使用JSON.NET来反序列化JSON.我写了一篇关于如何将JSON反序列化为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);
Run Code Online (Sandbox Code Playgroud)

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

注意: 我通常反序列化dynamic,所以我假设这样NameValueCollection可行.但是,我还没有确认它是否确实存在.