C#
Beginner
1 min read
Working with JSON and CSV Files
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);