Comments in JSON

#c-sharp #json

Written by Anders Marzi Tornblad

Normally, JSON doesn't allow for comments. However, if you're using JSON for configuration files, you may want to add comments to your JSON files. Here's how to support that in C#.

An example configuration file

Let's say we have a configuration file that looks like this:

{
    "domains": [
        /* Main business domains */
        "example.com",
        "example.org",

        /* Country-specific domains */
        "example.se",
        "example.it"
    ]
}
config.json

In C#, you can define a configuration class and decorate its properties with the JsonPropertyName attribute:

public class Configuration
{
    [JsonPropertyName("domains")]
    public string[] Domains { get; set; } = Array.Empty<string>();
}
Configuration.cs

To read this configuration file, you can use the JsonSerializer.Deserialize method and pass in a JsonSerializerOptions object with the ReadCommentHandling property set to JsonCommentHandling.Skip:

public class Configuration
{
    [JsonPropertyName("domains")]
    public string[] Domains { get; set; } = Array.Empty<string>();

    /* Call this method to load the configuration from a file */
    public static Configuration? Load(string path)
    {
        if (File.Exists(path))
        {
            using var json = File.OpenRead(path);
            var options = new JsonSerializerOptions {
                ReadCommentHandling = JsonCommentHandling.Skip
            };
            return JsonSerializer.Deserialize<Configuration>(json, options);
        }
        else
        {
            return null;
        }
    }
}
Configuration.cs

This method does not require any external libraries or NuGet packages. It's built into the System.Text.Json namespace.If you normally write your configuration files by hand, this method will allow you to add comments to your configuration files.