Parse JSON String in C#

In .NET, System.Text.Json namespace provides a class JsonSerializer with two static methods, JsonSerializer.Serialize and JsonSerializer.Deserialize.  The JsonSerializer.Deserialize method is used to parse a JSON string into an object and read its member values.

Here is an example of a C# object that was used to create JSON data.

public class CSharpMember
{
    public string Name { get; set; }
    public string Bio { get; set; }
    public DateTime JoinDate { get; set; }
    public bool Author { get; set; }
}

The JSON string created for the above object looks like this.

// Get JSON string 
string jsonMemberString = "{\"Name\":\"Mahesh Chand\",\"Bio\":\"Software developer\"," +
    "\"JoinDate\":\"2000-01-01T00:00:00-00:00\",\"Author\":true}";

You can call the JsonSerializer.Deserialize the method to deserialize the string into an object. 

// Deserialize JSON string into an object 
CSharpMember member = JsonSerializer.Deserialize<CSharpMember>(jsonMemberString);

Once the JSON string is deserialized into an object, now it's easy to read its values via the object members.

// Use Object's members to read/parse data 
Console.WriteLine($"Name: {member.Name}");
Console.WriteLine($"Bio: {member.Bio}");
Console.WriteLine($"JoinDate: {member.JoinDate}");
Console.WriteLine($"Author: {member.Author}");

The output of this program looks like the following:

Deserialize JSON string
Name: Mahesh Chand
Bio: Software developer
JoinDate: 12/31/1999 7:00:00 PM
Author: True

Download the attached program to get the complete program.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.