Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Deserialize JSON with C#

4.55/5 (8 votes)
14 Jun 2011CPOL 106.3K  
.NET Framework actually has this functionality built-in.The object is this one: system.web.script.serialization.javascriptserializer.aspx[^]I use this a lot and it works as expected.Here's 2 examples:1. Dumb deserializationHere's the easyest way, where you get what you...
.NET Framework actually has this functionality built-in.
The object is this one: system.web.script.serialization.javascriptserializer.aspx[^]

I use this a lot and it works as expected.

Here's 2 examples:

1. Dumb deserialization
Here's the easyest way, where you get what you give.
Note that I deliberatly added one more property to the last object but the deserializer doesn't bother about that. It will return an array of objects. Deal with it as you wish.
C#
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
Object obj = s.DeserializeObject("[{name:\"Alex\", age:\"34\"}, {name:\"Code\", age:\"55\", size:180}]");


2. Typed deserialization
This one is much smarter. It will convert each item into the passed object and return a List<mytype>.
Note that I've kept the extra property on the last object even knowing that myType doesn't have a match property for it.
XML
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
List<myObject> obj = s.Deserialize<List<myObject>>("[{name:\"Alex\", age:\"34\"}, {name:\"Code\", age:\"55\", size:180 }]");

C#
public class myObject
{
    public string name { get; set; }
    public int age { get; set; }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)