Mohanapriya R Mohanapriya R
Updated date May 20, 2024
In this article, we will learn to convert strings to JSON in C#. Learn the basics of JSON serialization using the built-in System.Text.Json library.

Converting Strings to JSON in C#

C# offers a built-in library called System.Text.Json that simplifies JSON serialization. This library provides the JsonSerializer class, which enables easy conversion between C# objects and JSON strings. Here is the program,

using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        // Input string representing person's information
        string personInfo = "{\"Name\":\"Mano\",\"Age\":30,\"City\":\"Chennai\"}";

        // Deserialize the string to a C# object
        Person person = JsonSerializer.Deserialize<Person>(personInfo);

        // Output the deserialized object
        Console.WriteLine("Deserialized Person:");
        Console.WriteLine($"Name: {person.Name}");
        Console.WriteLine($"Age: {person.Age}");
        Console.WriteLine($"City: {person.City}");

        // Serialize the object back to a JSON-formatted string
        string jsonOutput = JsonSerializer.Serialize(person);
        Console.WriteLine("\nSerialized JSON:");
        Console.WriteLine(jsonOutput);
    }
}

// Define a simple Person class for demonstration
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

Output:

Deserialized Person:
Name: Mano
Age: 25
City: Chennai

Serialized JSON:
{"Name":"Mano","Age":25,"City":"Chennai"}

Comments (0)

There are no comments. Be the first to comment!!!