232

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?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Justin
  • 42,716
  • 77
  • 201
  • 296
  • 1
    @Greg: I actually recommend the `JavaScriptSerializer` over MS's version as it won't accept anything else but WCF's custom JSON formatting (e.g. date fields that look like dates but aren't surrounded in DATE() fail miserably) – Brad Christie Jan 06 '11 at 01:50
  • Also, look at this [Parsing JSON objects with JavascriptSerializer in .NET](http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/) article, which is actually a great tutorial. – scatmoi Oct 23 '12 at 17:50
  • Where are you getting JavaScriptSerializer? It is unrecognized in my C# .NET 3.5 project. – B. Clay Shannon-B. Crow Raven Oct 15 '13 at 20:47
  • 1
    @B. Clay Shannon This resolved it for me http://stackoverflow.com/questions/7000811/cannot-find-javascriptserializer-in-net-4-0 – Fuzzybear Feb 27 '15 at 18:05
  • You can use `JavaScriptSerializer ` for this purpose without any issues.I will provide answer below . – AHAMED AAQIB Nov 21 '20 at 03:03

16 Answers16

306

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.

Legends
  • 21,202
  • 16
  • 97
  • 123
tripletdad99
  • 3,077
  • 2
  • 12
  • 2
  • The "T" type class you end up creating can be partial and doesn't need to be an exact copy of the full response that includes every JSON property. You can de-serialize exactly what you need although the hierarchy needs to match. – Prashanth Subramanian Jan 10 '21 at 05:07
138

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

  class Test {

      String test; 

      String getTest() { return test; }
      void setTest(String test) { this.test = test; }

  }

Then your deserialization code would be:

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

More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx

Mattiavelli
  • 888
  • 2
  • 9
  • 22
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • 1
    But in pointed article autoproperties are used. It's worth mentioning too. – Ivan Kochurkin Sep 18 '12 at 12:50
  • 11
    Sorry, but this code sample does not work. DeserializeObject gives an exception. Use var routes_list = serializer.Deserialize("{\"test\":\"some data\"}"); instead. Also, you don't need get/setTest( ), and String test, should be public. This looks more like java than C#. – dvallejo Oct 08 '13 at 16:47
  • as Dan Vallejo mentioned, this is an incorrect solution. After all, setTest(String test) is not returning, which is compile error as well. – Payam Aug 18 '14 at 03:05
  • 1
    Can also use this : json_serializer.Deserialize("{ \"test\":\"some data\" }"); //instead of (Test)json_serializer..... – Bashar Abu Shamaa Dec 23 '15 at 12:26
  • 2
    If you are unsure of the format for your class object, try this [link](http://json2csharp.com/). It translates your Json string into the right classes. Saved me a ton of time! – jade290 Jan 22 '16 at 16:03
59

You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:

var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);

If you want to use the dynamic keyword, you can read how here.

If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

class MyProgram {
    struct MyObj {
        public string test { get; set; }
    }

    static void Main(string[] args) {
        var json_serializer = new JavaScriptSerializer();
        MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
        Console.WriteLine(routes_list.test);

        Console.WriteLine("Done...");
        Console.ReadKey(true);
    }
}
Community
  • 1
  • 1
mattmc3
  • 17,595
  • 7
  • 83
  • 103
  • Doing: json_serializer = new JavaScriptSerializer(); object routes_list = (IDictionary)json_serializer.DeserializeObject("{ \"test\":\"some data here\" }"); Still getting 'routes_list' does not exist in the current context. – Justin Jan 06 '11 at 02:00
  • 1
    Don't use `object routes_list`. Use `var` or explicitly repeat yourself and declare routes_list as an IDictionary. – mattmc3 Jan 06 '11 at 02:06
35

Using dynamic object with JavaScriptSerializer.

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];

//test Result = "some data"
İbrahim Özbölük
  • 3,162
  • 23
  • 20
20

Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

one line code solution.

var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Jsonstring);

Myclass oMyclass = Newtonsoft.Json.JsonConvert.DeserializeObject<Myclass>(Jsonstring);
MSTdev
  • 4,507
  • 2
  • 23
  • 40
20

You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.

Class for the type of object you receive:

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }

}

Code:

static void Main(string[] args)
{

      string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";

      User user = JsonConvert.DeserializeObject<User>(json);

      Console.ReadKey();
}

this is a very simple way to parse your json.

16

Here's a simple class I cobbled together from various posts.... It's been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.

The below code can be run in LinqPad to test it out by:

  • Right clicking on your script tab in LinqPad, and choosing "Query Properties"
  • Referencing the "System.Web.Extensions.dll" in "Additional References"
  • Adding an "Additional Namespace Imports" of "System.Web.Script.Serialization".

Hope it helps!

void Main()
{
  string json = @"
  {
    'glossary': 
    {
      'title': 'example glossary',
        'GlossDiv': 
        {
          'title': 'S',
          'GlossList': 
          {
            'GlossEntry': 
            {
              'ID': 'SGML',
              'ItemNumber': 2,          
              'SortAs': 'SGML',
              'GlossTerm': 'Standard Generalized Markup Language',
              'Acronym': 'SGML',
              'Abbrev': 'ISO 8879:1986',
              'GlossDef': 
              {
                'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                'GlossSeeAlso': ['GML', 'XML']
              },
              'GlossSee': 'markup'
            }
          }
        }
    }
  }

  ";

  var d = new JsonDeserializer(json);
  d.GetString("glossary.title").Dump();
  d.GetString("glossary.GlossDiv.title").Dump();  
  d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump();  
  d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump();    
  d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump();   
  d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump(); 
  d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump();   
}


// Define other methods and classes here

public class JsonDeserializer
{
  private IDictionary<string, object> jsonData { get; set; }

  public JsonDeserializer(string json)
  {
    var json_serializer = new JavaScriptSerializer();

    jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
  }

  public string GetString(string path)
  {
    return (string) GetObject(path);
  }

  public int? GetInt(string path)
  {
    int? result = null;

    object o = GetObject(path);
    if (o == null)
    {
      return result;
    }

    if (o is string)
    {
      result = Int32.Parse((string)o);
    }
    else
    {
      result = (Int32) o;
    }

    return result;
  }

  public object GetObject(string path)
  {
    object result = null;

    var curr = jsonData;
    var paths = path.Split('.');
    var pathCount = paths.Count();

    try
    {
      for (int i = 0; i < pathCount; i++)
      {
        var key = paths[i];
        if (i == (pathCount - 1))
        {
          result = curr[key];
        }
        else
        {
          curr = (IDictionary<string, object>)curr[key];
        }
      }
    }
    catch
    {
      // Probably means an invalid path (ie object doesn't exist)
    }

    return result;
  }
}
Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
15

As tripletdad99 said

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

but if you don't want to create an extra object you can make it with Dictionary instead

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);
Ognyan Dimitrov
  • 6,026
  • 1
  • 48
  • 70
stanimirsp
  • 2,548
  • 2
  • 26
  • 36
10

add this ddl to reference to your project: System.Web.Extensions.dll

use this namespace: using System.Web.Script.Serialization;

public class IdName
{
    public int Id { get; set; }
    public string Name { get; set; }
}


   string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
   var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);

   string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
   var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
8

Another fast and easy way to semi-automate these steps is to:

  1. take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down.
  2. Update the name in the top left to your class name, it defaults to "Welcome".
  3. In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.
  4. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can now use code like:

    WebClient client = new WebClient();

    string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");

    var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);

Jason Hitchings
  • 667
  • 8
  • 10
8

Copy your Json and paste at textbox on json2csharp and click on Generate button.

A cs class will be generated use that cs file as below

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

Where RootObject is the name of the generated cs file;

Wictor Chaves
  • 957
  • 1
  • 13
  • 21
Islam
  • 129
  • 1
  • 1
1

Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.

JsonTextReader reader = null;
try
{
    WebClient webClient = new WebClient();
    JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
    reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
    reader.SupportMultipleContent = true;
}
catch(Exception)
{}

JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);
MNie
  • 1,347
  • 1
  • 15
  • 35
Bhaskar
  • 49
  • 2
0

First you have to include library like:

using System.Runtime.Serialization.Json;

DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";

using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
    BlogSite b = (BlogSite)desc.ReadObject(ms);
    Console.WriteLine(b.Name);
    Console.WriteLine(b.Description);
}
0xdb
  • 3,539
  • 1
  • 21
  • 37
0

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

  public class Student
{
   public string FirstName {get;set:}
   public string LastName {get;set:}
   public int[] Grades {get;set:}
}

public static Student ConvertToStudent(string std)
{
  var serializer = new JavaScriptSerializer();

  Return serializer.Deserialize<Student>(std);
 }
AHAMED AAQIB
  • 336
  • 4
  • 12
0

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

using System.Text.Json;
...
var options = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });
var result = JsonSerializer.Deserialize<List<T>>(json, options);

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

System.Text.Json is available in: .NET Core 2.0 and above .NET Framework 4.6.1 and above

ping
  • 663
  • 6
  • 13
0

For users using .Net Core 3.1 or newer

Or, you can use the new System.Text.Json library as follows, which works after and including .Net Core 3.1:

...
var result = System.Text.Json.JsonSerializer.Deserialize<T>(jsonString);

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