65.9K
CodeProject is changing. Read more.
Home

Deserialize JSON with C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.55/5 (8 votes)

Jun 14, 2011

CPOL
viewsIcon

106296

.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.
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. Note that I've kept the extra property on the last object even knowing that myType doesn't have a match property for it.
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 }]");
public class myObject
{
    public string name { get; set; }
    public int age { get; set; }
}
Deserialize JSON with C# - CodeProject