SyntaxStudy
Sign Up
C# Working with JSON and CSV Files
C# Beginner 1 min read

Working with JSON and CSV Files

`System.Text.Json` is the built-in, high-performance JSON library in .NET. It provides `JsonSerializer.Serialize` and `JsonSerializer.Deserialize` for straightforward object-to-JSON and JSON-to-object conversion. `JsonSerializerOptions` controls naming policies, indentation, and handling of null values and unknown properties. Source generation (available since .NET 6) pre-computes serialisation logic at compile time via a `JsonSerializerContext` subclass. This avoids runtime reflection, cuts startup time, and is required for Native AOT publishing. Decorate the context class with `[JsonSerializable(typeof(T))]` attributes for each type you need. For CSV, the `CsvHelper` NuGet package is the community standard. It handles quoting, escaping, custom field mapping via class maps, and async reading/writing. For simple use cases, parsing a CSV manually with `string.Split(',')` works, but edge cases like quoted fields containing commas make a library preferable.
Example
// JSON serialisation with System.Text.Json and source generation

using System.Text.Json;
using System.Text.Json.Serialization;

record ProductDto(
    [property: JsonPropertyName("product_id")]   int    Id,
    [property: JsonPropertyName("product_name")] string Name,
    [property: JsonPropertyName("unit_price")]   decimal Price
);

// Source-generation context (zero-reflection, AOT-safe)
[JsonSerializable(typeof(ProductDto))]
[JsonSerializable(typeof(List<ProductDto>))]
partial class AppJsonContext : JsonSerializerContext { }

var options = new JsonSerializerOptions
{
    WriteIndented    = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

var products = new List<ProductDto>
{
    new(1, "Laptop",   999.99m),
    new(2, "Keyboard",  79.99m),
};

// Serialize
string json = JsonSerializer.Serialize(products, AppJsonContext.Default.ListProductDto);
Console.WriteLine(json);

// Write to file and read back
string path = Path.Combine(Path.GetTempPath(), "products.json");
await File.WriteAllTextAsync(path, json);

string raw = await File.ReadAllTextAsync(path);
var restored = JsonSerializer.Deserialize(raw, AppJsonContext.Default.ListProductDto);
Console.WriteLine($"Restored {restored?.Count} products.");

// Manual CSV parsing (simple case)
string csv = "1,Laptop,999.99\n2,Keyboard,79.99";
foreach (string line in csv.Split('\n'))
{
    var cols = line.Split(',');
    Console.WriteLine($"Id={cols[0]}, Name={cols[1]}, Price={cols[2]}");
}

File.Delete(path);