Dofactory.com
Dofactory.com

How to turn an object into a JSON string in C#?

A JSON serializer is available in the System.Text.Json namespace.   It's included in the .NET Core shared framework. Here is an example


var obj = new Person
{
    FirstName = "Sander",
    LastName = "Chaney",
    Email = "schaney@gmail.com",
    DateOfBirth = new MyDate
    {
        Year = 1988,
        Month = 4,
        Day = 30
    }
};

var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);

You can also achieve this by using Newtonsoft.Json. Install Newtonsoft.Json from NuGet and then:


var obj = new Person
{
    FirstName = "Sander",
    LastName = "Chaney",
    Email = "schaney@gmail.com",
    DateOfBirth = new MyDate
    {
        Year = 1988,
        Month = 4,
        Day = 30
    }
};

var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Console.WriteLine(json);


Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.