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
employee
object instance of the Employee
class.Employee employee = JsonConvert.DeserializeObject<Employee>(json);
employee.Titles
is a List<string>
type, we use the foreach
loop construct to loop through each item in that List
.