Home  >  Article  >  Backend Development  >  C# Create JSON Object

C# Create JSON Object

WBOY
WBOYOriginal
2024-09-03 15:31:12712browse

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);

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();
}

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();
}
}
}

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();
}
}
}

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();
}
}
}

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:
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
Previous article:C# TuplesNext article:C# Tuples