Convert JSON String To C# Object

Justin picture Justin · Jan 6, 2011 · Viewed 685.3k times · Source

Trying to convert a JSON string into an object in C#. Using a really simple test case:

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

The problem is that routes_list never gets set; it's an undefined object. Any ideas?

Answer

tripletdad99 picture tripletdad99 · Feb 15, 2013

Or, you can use the Newtownsoft.Json library as follows:

using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);

Where T is your object type that matches your JSON string.