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)