json.net Getting started with json.net How to Deserialize JSON data to Object using Json.Net in C#

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The following example shows how you can deserialize a JSON string containing into an Object (i.e. into an instance of a class).

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
                    
public class Program
{
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsManager { get; set; }
        public DateTime JoinedDate { get; set; }
        public IList<string> Titles { get; set; }
    }
    
    public static void Main()
    {
        string json = @"{
                          'FirstName': 'Shiva',
                          'LastName': 'Kumar',
                          'IsManager': true,
                          'JoinedDate': '2014-02-10T00:00:00Z',
                          'Titles': [
                            'Sr. Software Engineer',
                            'Applications Architect'
                          ]
                        }";
        
        Employee employee = JsonConvert.DeserializeObject<Employee>(json);

        Console.WriteLine(employee.FirstName);
        Console.WriteLine(employee.LastName);
        Console.WriteLine(employee.JoinedDate);
        foreach (string title in employee.Titles)
        {
            Console.WriteLine("  {0}", title);    
        }
    }
}

If you run this console program, the output of the various Console.WriteLine statements will be as follows.

Shiva
Kumar
2/10/2014 12:00:00 AM
  Sr. Software Engineer
  Applications Architect

Few things to note

  1. The following line performs the actual deserialization of the data in the json string into the employee object instance of the Employee class.

Employee employee = JsonConvert.DeserializeObject<Employee>(json);

  1. Since employee.Titles is a List<string> type, we use the foreach loop construct to loop through each item in that List.


Got any json.net Question?