Friday, June 12, 2026

Serializing data into JSON format using Newtonsoft.Json package in Console App

The Newtonsoft.Json package provides classes that are used to implement the core services of the framework. It provides methods for conversion between .NET types and JSON types.

Serializing data into JSON format

Install Newtonsoft.Json package Version="13.0.4" in your project before running the following code. The code displays student list object in JSON format in console. It also generates a json.txt text file in D:/ drive and writes student data in JSON format.

using Newtonsoft.Json;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            Student student1 = new Student()
            {
                id = 1,
                FirstName = "Ajeet",
                LastName = "Kumar",
                Age = 44
            };
            Student student2 = new Student()
            {
                id = 2,
                FirstName = "Rakesh",
                LastName = "Roshan",
                Age = 42
            };
            students.Add(student1);
            students.Add(student2);
            string stringOutput = JsonConvert.SerializeObject(students);
            Console.WriteLine(stringOutput);

            JsonSerializer serializer = new JsonSerializer();
            // file is created in the d drive with name json.txt
            using (StreamWriter streamw = new StreamWriter(@"d:\json.txt"))
            // JsonTextWriter is used to write JSON data to a stream
            using (JsonWriter jsonWriter = new JsonTextWriter(streamw))
            {
                serializer.Serialize(jsonWriter, students);
            }
            Console.ReadLine();
        }
    }
    class Student
    {
        public int id { get; set; }
        public string FirstName { get; set; } = string.Empty;
        public string LastName { get; set; } = string.Empty;
        public int Age { get; set; }
    }
}
OUTPUT
[{"id":1,"FirstName":"Ajeet","LastName":"Kumar","Age":44},{"id":2,"FirstName":"Rakesh","LastName":"Roshan","Age":42}]


No comments:

Post a Comment

Hot Topics