serialize json array c# code example

Example 1: c# serialize json

using System.Text.Json;

//Serialize
var jsonString = JsonSerializer.Serialize(yourObject);

// Deserialize
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);

Example 2: c# json serialize

string jsonString = JsonSerializer.Serialize(weatherForecast);

Example 3: serialize collection c#

Product p1 = new Product
{
    Name = "Product 1",
    Price = 99.95m,
    ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
};
Product p2 = new Product
{
    Name = "Product 2",
    Price = 12.50m,
    ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};

List<Product> products = new List<Product>();
products.Add(p1);
products.Add(p2);

string json = JsonConvert.SerializeObject(products, Formatting.Indented);
//[
//  {
//    "Name": "Product 1",
//    "ExpiryDate": "2000-12-29T00:00:00Z",
//    "Price": 99.95,
//    "Sizes": null
//  },
//  {
//    "Name": "Product 2",
//    "ExpiryDate": "2009-07-31T00:00:00Z",
//    "Price": 12.50,
//    "Sizes": null
//  }
//]