How can I convert from JsonString to NameValueCollection

596 Views Asked by At

I have a JSON string like below:

"\"{\\\"PersonNumber\\\":\\\"4537\\\",\\\"PersonName\\\":\\\"Jenny\\\"}\""

I want to convert this JSON to NameValueCollection and I have tried below codes. but I am getting an error :

string jsonString= "\"{\\\"PersonNumber\\\":\\\"4537\\\",\\\"PersonName\\\":\\\"Jenny\\\"}\""
System.Web.Script.Serialization.JavaScriptSerializer jss1;
NameValueCollection nvc1;
jss1 = new System.Web.Script.Serialization.JavaScriptSerializer();
nvc1 = new NameValueCollection();
try { nvc1 = jss1.Deserialize<NameValueCollection>(jsonString); } catch { }

Error:

Cannot convert object of type 'System.String' to type 'System.Collections.Specialized.NameValueCollection'

Where am I making a mistake?

2

There are 2 best solutions below

0
Dan On

If you specifically need a NameValueCollection then the simplest way is simply use DeserializeObject and then add the items to a NameValueCollection like so:

string jsonString= "\"{\\\"PersonNumber\\\":\\\"4537\\\",\\\"PersonName\\\":\\\"Jenny\\\"}\""

System.Web.Script.Serialization.JavaScriptSerializer jss1;
NameValueCollection nvc1;
IDictionary<string, object> dict;

jss1 = new System.Web.Script.Serialization.JavaScriptSerializer();
nvc1 = new NameValueCollection();
dict = jss1.DeserializeObject(jsonString);

foreach (var kvPair in dict)
{
  nvc1.Add(kvPair.Key, kvPair.Value);
}
0
Jamiec On

Given a pretty simple extension method on Dictionary<string,T>:

public static class DictionaryExtensions
{
    public static NameValueCollection ToNameValueCollection<T>(this IDictionary<string, T> dictionary)
    {
        var collection = new NameValueCollection();
        foreach(var pair in dictionary)
            collection.Add(pair.Key, pair.Value?.ToString());
        return collection;
    }
}

This is as easy as deserializing your json to a dictionary and using the extension method:

var nvc = JsonConvert.DeserializeObject<Dictionary<string,string>>(jsonString)
                     .ToNameValueCollection();

Note: Uses Newtonsoft.Json, but any deserializer should be able to deserialize your jsonString directly to Dictionary<string,string>.

Live example: https://dotnetfiddle.net/vxqumd