JSON (JavaScript Object Notation) is one of the most widely used data interchange format. In a world of services based application, JSON plays a very important role for data transmission since it is very light weight when compared to XML. This means that, all applications we develop these days will have JSON handling. All the application frameworks including .NetFramework has in build support for manipulating JSON using various framework API. In .Net world, there is an open source framework called JSON.Net or Newtonsoft.Json for JSON manipulation. This component is the most widely used and most downloaded package in Nuget.org. The main advantage of this package over the .NetFramework provided API is, it works across multiple platforms like Silverlight, Windows Phone, Xamarin, etc. and the performance is way better than .NetFramework’s inbuilt API for JSON. This package helps developers to serialize .Net objects and collections to JSON string and deserialize them back to objects very easily.
Moving forward, let’s understand how to use this package to convert the .Net objects and collections to JSON and vice versa in Asp.Net MVC applications. Let’s create Asp.Net MVC 5.0 website in Visual Studio 2015 for this article.
As I said before, the JSON.Net is available as Nuget package. To add the JSON.Net package, right click your project in solution explorer and click “Manage Nuget Package..” Search Newtonsoft.Json and click Install to install the package.
Or you can use the command from Nuget Package Manager Console to get the latest JSON.Net package from Nuget.org.
Install-Package Newtonsoft.Json
For easy understanding, let’s use a simple Employee-Department model with Entity First Code First for data access.
Serializing and Deserializing To JSON
JSON.Net provides 2 class for serializing and Deserializing JSON. They are,
-
JsonConvert
This class can be used for simple serializing and Deserializing objects. The class exposes 2 methods JsonConvert.SerializeObject([object]) and JsonConvert.DeserializeObject<[object]>([jsonstring]) for this.
-
JsonSerializer
This class can be used to advanced scenarios like adding customization for specific types, etc. For example, we can add a custom converter to convert a specific object type values like JavaScriptDateTimeConverter to convert datetime type.
Serializing .Net Object to JSON And Vice Versa
To serialize an Employee object to JSON string, we can use the below code.
Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
string json = JsonConvert.SerializeObject(emp);
To deserialize a JSON string back to Employee object, we can use the below code.
Employee emp = JsonConvert.DeserializeObject<Employee>(json1);
json1 is a string variable with JSON content.
To serialize a .Net collection to JSON string,
IList<Employee> empList = db.Employees.Include("Department").OrderBy(e => e.EmployeeId).ToList();
string json = JsonConvert.SerializeObject(empList);
To deserialize json string to .Net Collection,
List<Employee> empList = JsonConvert.DeserializeObject<List<Employee>>(json2);
Json2 is a string variable with JSON content.
Note - You need to include the namsepace Newtonsoft.Json for the above code to work.
To understand better, let’s build a simple functionality to import and export JSON data using a simple database in next section.
Import and Export JSON data into Database Using Entity Framework Code First
Let’s build a simple functionality to import and export data using JSON format using the Employee-Department data model. The full source is attached at the bottom of this article for reference. We will build a page where it displays a list of employees from database with a link on each row to export the row as JSON and a button outside the grid to export all the employee rows into a JSON string. For simplicity, we will display the created JSON string the view. You can save it to a file in disk or stream it to user for downloading. Refer below.
The below 2 action methods will help us to serialize the employee objects to JSON. The view will display the content of ViewBag.json under the JSON Output section of the view as seen above.
[HttpPost]
public ActionResult ExportEmployeeAsJson(int id)
{
Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
ViewBag.json = JsonConvert.SerializeObject(emp);
return View("GetAllEmployeeData",db.Employees.Include("Department").OrderBy(e => e.EmployeeId));
}
[HttpPost]
public ActionResult ExportAllEmployeeAsJson()
{
IList<Employee> empList = db.Employees.Include("Department").OrderBy(e => e.EmployeeId).ToList();
ViewBag.json = JsonConvert.SerializeObject(empList);
return View("GetAllEmployeeData",empList);
}
Next, we will also provide a page to import data into database from JSON string.
The below 2 action methods will help us to get the JSON string from user and deserialize them to .Net object and import to the rows to database.
[HttpPost]
public ActionResult ImportEmployeeFromJson(string json1)
{
if (json1 != null && json1 != "")
{
Employee emp = JsonConvert.DeserializeObject<Employee>(json1);
db.Employees.Add(emp);
db.SaveChanges();
}
return View("SaveEmployeeFromJson", db.Employees.Include("Department").OrderBy(e => e.EmployeeId));
}
[HttpPost]
public ActionResult ImportEmployeesFromJson(string json2)
{
if (json2 != null && json2 != "")
{
IList<Employee> empList = JsonConvert.DeserializeObject<List<Employee>>(json2);
db.Employees.AddRange(empList);
db.SaveChanges();
}
return View("SaveEmployeeFromJson", db.Employees.Include("Department").OrderBy(e => e.EmployeeId));
}
Note – In a real-world application, you should perform some input validation before doing data uploads. JSON.Net supports JSON Schema validation for this purpose.
Download the source and see it in action. You have sample json.txt with sample data in the solution for upload.
Further Reading: Refer the official documentation here for more customization and understanding.