In this blog post, you will learn how to serialize and deserialize JSON objects using the Newtonsoft library with an example in C#. Keep reading on How to Convert JSON to Datatable in C#
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.
JSON supports the following two data structures,
- Collection of name/value pairs and,
- An ordered list of values.
How to Serialize and Deserialize objects using NewtonSoft JSON
Let’s create a console-based application to understand how to serialize an object to JSON NewtonSoft and NewtonSoft JSON Deserialize using C#.
Now you need to install the Newtonsoft JSON using Nuget Package in the application. You can visit to find the latest package https://www.nuget.org/packages/newtonsoft.json/.
Run the below command to install Newtonsoft JSON from the package mange console as shown below:-
Install-Package Newtonsoft.Json -Version 12.0.3
Now find the below example to implement Newtonsoft JSON serialization and deserialization:-
Program.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace ConsoleAppNewtonsoft { class Program { const string filePath = @"c:\data\json.txt"; static void Main(string[] args) { var product = new Product { Name = "eBooks", SerialNumbers = new List<int> { 101, 102, 103, 104 } }; Console.WriteLine("Object before serialization:"); Console.WriteLine("----------------------------"); Console.WriteLine(); product.Show(); Serialize(product); var deserialized = Deserialize(filePath); Console.WriteLine("Deserialized (json) string:"); Console.WriteLine("---------------------------"); Console.WriteLine(); Console.WriteLine(deserialized); } public static void Serialize(object obj) { var serializer = new JsonSerializer(); using (var sw = new StreamWriter(filePath)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, obj); } } public static object Deserialize(string path) { var serializer = new JsonSerializer(); using (var sw = new StreamReader(path)) using (var reader = new JsonTextReader(sw)) { return serializer.Deserialize(reader); } } } }
Product.cs
using System; using System.Collections.Generic; namespace ConsoleAppNewtonsoft { public class Product { public string Name { get; set; } public List<int> SerialNumbers { get; set; } public void Show() { Console.WriteLine("Name: " + Name); Console.WriteLine("Serial Numbers: " + string.Join<int>(",", SerialNumbers)); Console.WriteLine(); Console.WriteLine(); } } }

Conclusion
I hope you liked this article on NewtonSoft JSON Serialize C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply