Table of Contents
How we can Create JSON Object in C#?
Examples of C# Create JSON Object
Example #3
Conclusion
Home Backend Development C#.Net Tutorial C# Create JSON Object

C# Create JSON Object

Sep 03, 2024 pm 03:31 PM
c# c# tutorial

Before discussing how to create a JSON object in C#, let us first understand what JSON is. JSON stands for JavaScript Object Notation. It is a very lightweight text format which is used to exchange data. JSON can be expressed in three styles i.e. object, array, and string. Here, we will discuss the JSON object. A JSON object begins with “{” and ends with “}”. Data in JSON object is stored as key-value pair where a key and its value are separated by a colon “:” and each key-value pair is separated by a comma “,”.

Syntax:

The syntax to create JSON using Newtonsoft package is as follows:

ClassName objectName = new ClassName();
string jsonStr = JsonConvert.SerializeObject(objectName);
Copy after login

Explanation: In the above syntax, first we created the object of the class for which we need data in JSON format then we used JsonConvert.Serialize() method of Newtonsoft package and passed our class object as a parameter to this method which then returns a JSON string after converting the data of the object to JSON string.

After this, we can store this JSON data to a file using the below statements:

using(var streamWriter = new StreamWriter(filePath, true))
{
streamWriter.WriteLine(jsonStr.ToString());
streamWriter.Close();
}
Copy after login

In the above statements, we created an object of StreamWriter to write JSON data to a file specified by location ‘filePath’. Then, with the help of this object we have written JSON data to the file using the WriteLine() method.

How we can Create JSON Object in C#?

In C#, we can create JSON objects in many ways i.e. by using a .NET native library or by using third party packages.

If we want to use the native .NET library to create a JSON object then we need to add System. ServiceModel.Web as a reference to our project after this we will be able to import System.Runtime.Serialization.Json namespace in our code which contains a class called DataContractJsonSerializer which is responsible to serialize the objects to the JSON data and deserialize the JSON data to objects.

Apart from this, we can use third party packages to work with JSON. Like Newtonsoft.Json package. To install this package and to add it to our project, we need to follow below steps in visual studio:

  • Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

C# Create JSON Object

  • Under the ‘Browse’ tab search for “Newtonsoft.Json” package and select it from the results displayed then select your project to which you want to add this package.
  • Click on the install button.

C# Create JSON Object

After following these steps when we will check the references of our project then we will get “Newtonsoft.Json” added to it.

We can now import Newtonsoft.Json namespace in our code which contains a class called JsonConvert which provides methods for conversion between .NET types and JSON types.

Examples of C# Create JSON Object

Example showing the creation of JSON object using .NET native library.

Example #1

Code:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace ConsoleApp4
{
[DataContractAttribute]
public class Student
{
[DataMemberAttribute]
public int RollNo { get; set; }
[DataMemberAttribute]
public string FirstName { get; set; }
[DataMemberAttribute]
public string LastName { get; set; }
[DataMemberAttribute]
public string Address { get; set; }
[DataMemberAttribute]
public float TotalMarks { get; set; }
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
MemoryStream memoryStream = new MemoryStream();
//serializing object to JSON
DataContractJsonSerializer ser =
new DataContractJsonSerializer(student.GetType());
//writing JSON
ser.WriteObject(memoryStream, student);
memoryStream.Position = 0;
StreamReader streamReader = new StreamReader(memoryStream);
jsonStr = streamReader.ReadToEnd();
Console.WriteLine(jsonStr);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Copy after login

Output:

C# Create JSON Object

Example #2

Example showing the creation of JSON object using .NET native library and then writing the resulted JSON data to a file using StreamWriter.

Code:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace ConsoleApp4
{
[DataContractAttribute]
public class Student
{
[DataMemberAttribute]
public int RollNo;
[DataMemberAttribute]
public string FirstName;
[DataMemberAttribute]
public string LastName;
[DataMemberAttribute]
public string Address;
[DataMemberAttribute]
public float TotalMarks;
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
string filePath = @"E:\Content\student.json";
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
MemoryStream memoryStream = new MemoryStream();
//serializing object to JSON
DataContractJsonSerializer ser =
new DataContractJsonSerializer(student.GetType());
//writing JSON
ser.WriteObject(memoryStream, student);
memoryStream.Position = 0;
StreamReader streamReader = new StreamReader(memoryStream);
jsonStr = streamReader.ReadToEnd();
//checking if the file already exists
if (File.Exists(filePath))
{
//deleting file if it exists
File.Delete(filePath);
}
//creating StreamWriter to write JSON data to file
using (StreamWriter streamWriter = new StreamWriter(filePath, true))
{
streamWriter.WriteLine(jsonStr.ToString());
streamWriter.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Copy after login

Please find below the screenshot of the output from the above program in student.json file opened in notepad.

Output:

C# Create JSON Object

Example #3

Example showing the creation of JSON object using Newtonsoft package.

Code:

using System;
using Newtonsoft.Json;
namespace ConsoleApp4
{
public class Student
{
public int RollNo;
public string FirstName;
public string LastName;
public string Address;
public float TotalMarks;
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
//serializing student object to JSON string
jsonStr = JsonConvert.SerializeObject(student);
Console.WriteLine(jsonStr);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Copy after login

Output:

C# Create JSON Object

Conclusion

JSON objects are enclosed under curly braces and contain key-value pairs. A key and its value are separated by colon where the key must be string and value can be of any valid data type. Each key-value pair in the JSON object is separated by a comma.

The above is the detailed content of C# Create JSON Object. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

See all articles