Categories
c# deserialization dictionary json json.net

How can I deserialize JSON with C#?

539

I have the following code:

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);

The input in responsecontent is JSON, but it is not properly deserialized into an object. How should I properly deserialize it?

6

  • 7

    Hey you may want to try this link techblog.procurios.nl/k/n618/news/view/14605/14863/…

    – Vamsi

    Jul 8, 2011 at 5:44

  • 44

    There’s Json in System.Web.Helpers, there’s JsonQueryStringConverter in System.ServiceModel.Web, there’s JavascriptSerializer in System.Web.Script.Serialization, DataContractJsonSerializer in System.Runtime.Serialization.Json, heck MS has even decided to include third party Json.NET in its ASP.NET Web API. If you thought that wasn’t enough, MS is coming up with System.Json but currently is unfit for consumption. Way to go Microsoft way to go…. I choose by the best looking namespace.

    – nawfal

    Jun 15, 2015 at 10:55


  • 4

    @fusi the rest are in separate assemblies. Google the namespace/class name, you will find the assembly they are in msdn documentation. Just add reference to that assembly.

    – nawfal

    Aug 3, 2015 at 16:01


  • 1

    Just to complete, there is also JsonValue in Windows.Data.Json which is only for Windows 8 and above. I’m loving it. MS is on a mission 🙂

    – nawfal

    Aug 3, 2015 at 17:21

  • 6

    NewtonSoft has a comparison page on their site (might be biased but still interesting): newtonsoft.com/json/help/html/jsonnetvsdotnetserializers.htm. I especially liked the Nonsensical dictionary serialization row 🙂

    Aug 20, 2016 at 14:09


349

As was answered here – Deserialize JSON into C# dynamic object?

It’s pretty simple using Json.NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Or using Newtonsoft.Json.Linq :

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

4

  • 14

    @MaxHodges, you are right. I just used inline “magic strings” for demonstrating how to parse JSON string values. Didn’t want it to look complex with escaping double quotes. In real code we usually have JSON strings obtained from somewhere as variables or passed as parameters.

    Jan 3, 2016 at 20:26

  • 5

    Without .net 4 you don’t have ‘dynamic’ keyword. You can use ‘var stuff’ for declaration and instead of ‘stuff.Name’ and ‘stuff.Address.City’ you have ‘stuff[“Name”]’ and ‘stuff[“Address”][“City”]’ respectively.

    – Fil

    Jul 17, 2017 at 22:57

  • 3

    @Fil That gives you a value of type object, and you can’t use indexing on a object.

    – Alex

    Jul 18, 2017 at 8:15

  • @Alex i’m pretty sure the Newtonsoft.Json variant returns a JObject. also, don’t use Json.NET, even VS uses Newtonsoft.Json by now. can now even be used in VSIX without adding it to the package

    Jun 28, 2020 at 23:18

153

Here are some options without using third party libraries:

// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());

// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);

// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);

See the link for more information about System.Web.Helpers.Json.

Update: Nowadays the easiest way to get the Web.Helpers is to use the NuGet package.


If you don’t care about earlier windows versions you can use the classes of the Windows.Data.Json namespace:

// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());

10

  • 1

    Why I don’t see System.Web.Helpers in my ASP.NET web site (4.5)? XElement, XPathSelectElement are not known for my VisualStudio. How to educate it?

    – Budda

    Aug 5, 2014 at 4:50

  • Well, you have to add references for the corresponding libraries (as written in the comments above), see this article for more info. Also, this question might be of interest.

    – qqbenq

    Aug 5, 2014 at 9:29


  • 2

    I used the Web.Helpers method described here but ran into an issue that was solved by this post: stackoverflow.com/questions/7066726/…

    – Alex

    Jan 20, 2015 at 15:50

  • 1

    it working with WPF.By using following namespace using System.Runtime.Serialization.Json; using System.Xml.XPath; using System.Xml.Linq;

    Feb 26, 2016 at 8:11


  • 4

    Json.Net is hardly a third party component anymore. Microsoft use it themselves these days. It’s the default serilizer on Web API.

    – Liam

    Aug 5, 2016 at 9:06