Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

c# - how to convert NameValueCollection to JSON string?

I tried:

  NameValueCollection Data = new NameValueCollection();
  Data.Add("foo","baa");
  string json = new JavaScriptSerializer().Serialize(Data);

it returns: ["foo"] I expected {"foo" : "baa"} How do I to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to serialize NameValueCollection is by first converting it to Dictionary and then serialize the Dictionary. To convert to dictionary:

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:

public static class NVCExtender
{
    public static IDictionary<string, string> ToDictionary(
                                        this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary(k => k, k => source[k]);
    }
}

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

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");

var dict = Data.ToDictionary();

Then you can serialize the dictionary:

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

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

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");
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:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...