Write JSON to a file

April 6, 2024 ยท View on GitHub

This sample writes LINQ to JSON objects to a file.

var videogameRatings = new JObject(
    new JProperty("Halo", 9),
    new JProperty("Starcraft", 9),
    new JProperty("Call of Duty", 7.5));

File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());

// write JSON directly to a file
using var file = File.CreateText(@"c:\videogames.json");
using var writer = new JsonTextWriter(file);
videogameRatings.WriteTo(writer);

snippet source | anchor