Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert json to NameValueCollection

Tags:

json

c#

.net

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

like image 298
James Avatar asked Jul 09 '12 16:07

James


People also ask

How to convert JSON file to dict Python?

JSON String to Python Dictionary To do this, we will use the loads() function of the json module, passing the string as the argument. json. loads(data_JSON) creates a new dictionary with the key-value pairs of the JSON string and it returns this new dictionary.

How do you convert a JSON string to a JSON Deserialization?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is a JSON converter?

A converter is a class that converts an object or a value to and from JSON. The System.Text.Json namespace has built-in converters for most primitive types that map to JavaScript primitives.


2 Answers

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.

like image 64
JP Richardson Avatar answered Sep 28 '22 09:09

JP Richardson


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

like image 35
Pranay Rana Avatar answered Sep 28 '22 09:09

Pranay Rana