JSON (JavaScript Object Notation) is THE standard design for human-readable data interchange. It is a light-weight, human-readable format for storing and transporting data. Since JSON works with a tree structure, it looks like
JSON is mainly used when data is sent from a server to a web page.
Create your new console project from Visual Studio.
Click File, New Project, Console Application.
Once the editor is opened, go to “Project”.
Click on “Manage NuGet Packages”.
Search “Newtonsoft.JSON” on Nuget Package Manager in the browse window and install it.
You can also install
Newtonsoft.JSON
from the terminal using this command:dotnet add package Newtonsoft.Json
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
studentInfo
that stores the name
, Roll
(as in roll number), and the list of courses each student is studying during the semester. We will output this information as a JSON string:class studentInfo
{
public int Roll {get; set;}
public string name {get; set;}
public List<string> courses {get; set;}
}
studentInfo
in the main function. In this example, I have named it student1
. Add relevant values to store in this class attribute:studentInfo student1 = new studentInfo()
{
Roll = 110,
name = "Alex",
courses = new List<string>()
{
"Math230",
"Calculus1",
"CS100",
"ML"
}
};
string stringjson = JsonConvert.SerializeObject(student1);
Console.WriteLine(stringjson);
// necessary libraries to be usedusing System;using System.Collections.Generic;using Newtonsoft.Json;namespace JsonParser{// Define a class to store values to be converted to JSONclass studentInfo{// Make sure all class attributes have relevant getter setter.// Roll Numberpublic int Roll {get; set;}// Name of the studentpublic string name {get; set;}// The List of courses studyingpublic List<string> courses {get; set;}}class HelloWorld{// Main functionstatic void Main(){// Creating a new instance of class studentInfostudentInfo student1 = new studentInfo(){// Roll numberRoll = 110,// Namename = "Alex",//list of coursescourses = new List<string>(){"Math230","Calculus1","CS100","ML"}};Console.WriteLine("JSON converted string: ");// convert to Json string by seralization of the instance of class.string stringjson = JsonConvert.SerializeObject(student1);Console.WriteLine(stringjson);}}}
JSON converted string:
{"Roll":110,"name":"Alex","courses":["Math230","Calculus1","CS100","ML"]}
Free Resources