The following example shows how you can use Json.Net to serialize the data in an C# Object's instance, to JSON string.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
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 class Program
{
public static void Main()
{
Employee employee = new Employee
{
FirstName = "Shiva",
LastName = "Kumar",
IsManager = true,
JoinedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Titles = new List<string>
{
"Sr. Software Engineer",
"Applications Architect"
}
};
string json = JsonConvert.SerializeObject(employee, Formatting.Indented);
Console.WriteLine(json);
}
}
If you run this console program, the output of the Console.WriteLine(json)
will be
{
"FirstName": "Shiva",
"LastName": "Kumar",
"IsManager": true,
"JoinedDate": "2013-01-20T00:00:00Z",
"Titles": [
"Sr. Software Engineer",
"Applications Architect"
]
}
Few things to note
The following line performs the actual serialization of the data inside the employee
class instance into a json string
string json = JsonConvert.SerializeObject(employee, Formatting.Indented);
The parameter Formatting.Indented
tells Json.Net to serialize the data with indentation and new lines. If you don't do that, the serialized string will be one long string with no indentation or line breaks.