save dictionary to json in csharp

To save a dictionary as a json file in C#, you can use the System.Text.Json namespace that is available in .NET Core 3.0 or later. Follow these steps:

  1. Start by adding the System.Text.Json namespace to your project:
main.cs
using System.Text.Json;
24 chars
2 lines
  1. Create a Dictionary<TKey, TValue> object that you want to save as json.
main.cs
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("apple", 2);
myDict.Add("banana", 3);
113 chars
4 lines
  1. Serialize the dictionary object to JSON using the JsonSerializer.Serialize() method. The Serialize() method will return a JSON formatted string.
main.cs
string jsonString = JsonSerializer.Serialize(myDict);
54 chars
2 lines
  1. Save the JSON string to a file using C#'s built-in file I/O functionality.
main.cs
File.WriteAllText(@"C:\data\myDictionary.json", jsonString);
61 chars
2 lines

The complete code to save a dictionary as a json file in C# would look something like this:

main.cs
using System.Text.Json;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> myDict = new Dictionary<string, int>();
        myDict.Add("apple", 2);
        myDict.Add("banana", 3);

        string jsonString = JsonSerializer.Serialize(myDict);
        File.WriteAllText(@"C:\data\myDictionary.json", jsonString);
    }
}
411 chars
17 lines

gistlibby LogSnag