Create JSON String in C# | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

Create JSON String in C#

Date- May 31,2023

4467

Certainly! Here's an example of how you can create a JSON string in C# using the Newtonsoft.Json library:

using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        // Create an object to be serialized to JSON
        var person = new Person
        {
            Name = "John Doe",
            Age = 30,
            Address = "123 Main St",
            City = "New York"
        };

        // Convert the object to a JSON string
        string jsonString = JsonConvert.SerializeObject(person, Formatting.Indented);

        // Output the JSON string
        Console.WriteLine(jsonString);
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
}

In this example, we define a Person class with some properties. We then create an instance of the Person class with some sample data. Using the JsonConvert.SerializeObject() method from the Newtonsoft.Json library, we convert the person object to a JSON string. Finally, we output the JSON string to the console.

Make sure to include the Newtonsoft.Json namespace by adding the following line at the top of your C# file:

using Newtonsoft.Json;
You'll also need to have the Newtonsoft.Json NuGet package installed in your project. You can do this by right-clicking on your project in Visual Studio, selecting "Manage NuGet Packages," and searching for "Newtonsoft.Json" to install it.

Comments

Tags

Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
ITextSharp
Export to Pdf
AspNet Core
AspNet
C#
View to Pdf in Aspnet
Scheduler
Fibonacci series in Java
Display Fibonacci Series
First C# Program
What is C?
C
C Programming
CodeLobster
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2026 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts