James
James

Reputation: 31778

How to convert json to NameValueCollection

How could you convert a string of JSON to a C# NameValueCollection simply, preferably without using a 3rd party parser?

Upvotes: 6

Views: 21810

Answers (3)

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14595

If your JSON contains nested objects whithin it the solution below will handle them properly (based on JSON.NET, but you can adapt to the JSON parser of your choice).

This usage example:

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]"]);

Produces the following output:

paid
09.10.2019 17:30
+5511987654321
123456789
doc_id

And here's the implementation:

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

Upvotes: 0

JP Richardson
JP Richardson

Reputation: 39425

I'm not sure why everyone is still recommending JSON.NET for deserialization of JSON. I wrote a blog post on how to deserialize JSON to C#.

In short, it's like this:

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

Be sure to add a reference to System.Web.Extensions.dll.

Note: I usually deserialize to dynamic, so I'm assuming that NameValueCollection would work. However, I haven't verified if it actually does.

Upvotes: 9

Pranay Rana
Pranay Rana

Reputation: 176946

EDIT

Pure .net solution without third party development have look : JavaScriptSerializer – Dictionary to JSON Serialization and Deserialization


make use of Json.NET

string jsonstring = @"{""keyabc"":""valueabc"",""keyxyz"":""valuexyz""}";

Dictionary<string, string> values = 
   JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonstring);

Check @jon answer suggest same : .Net Linq to JSON with Newtonsoft JSON library

Upvotes: 4

Related Questions