NameValueCollection 转换为 Json

深藏阁楼爱情的钟 2022-08-09 06:23 258阅读 0赞

参阅:http://stackoverflow.com/questions/7003740/how-to-convert-namevaluecollection-to-json-string

  1. thenvc.AllKeys.ToDictionary(k => k, k => thenvc[k]);

If you need to do the conversion frequently, you can also create an extension method to NameValueCollection:

  1. public static class NVCExtender
  2. {
  3. public static IDictionary<string, string> ToDictionary(
  4. this NameValueCollection source)
  5. {
  6. return source.AllKeys.ToDictionary(k => k, k => source[k]);
  7. }
  8. }

so you can do the conversion in one line like this:

  1. NameValueCollection Data = new NameValueCollection();
  2. Data.Add("Foo", "baa");
  3. var dict = Data.ToDictionary();

Then you can serialize the dictionary:

  1. var json = new JavaScriptSerializer().Serialize(dict);
  2. // you get {"Foo":"baa"}

But NameValueCollection can have multiple values for one key, for example:

  1. NameValueCollection Data = new NameValueCollection();
  2. Data.Add("Foo", "baa");
  3. Data.Add("Foo", "again?");

If you serialize this you will get {"Foo":"baa,again?"}.

You can modify the converter to produce IDictionary<string, string[]> instead:

  1. public static IDictionary<string, string[]> ToDictionary(
  2. this NameValueCollection source)
  3. {
  4. return source.AllKeys.ToDictionary(k => k, k => source.GetValues(k));
  5. }

So you can get serialized value like this: {"Foo":["baa","again?"]}.

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读