How do I add comments to Json.NET output?

The Json.NET JsonSerializer doesn't automatically output comments when serializing. You'll need to write your JSON manually, either using JsonTextWriter or LINQ to JSON if you want comments


The problem is that JSON as a file format doesn't support comments. One thing you could do - if the application reading the JSON file allows it - is to use additional properties as comments as suggested in this question: Can comments be used in JSON?


As @RoToRa already said, JSON does not permit comments.

If you still want comments, and you want to output correct JSON, you could just make the comments part of the actual JSON data by changing the data layout. For example:

{
    "MyString": {
        "doc":   "My documentation string",
        "value": "Test"
    } 
}

Well there is something one can do in order to add a comment to the output, but I would not do it except out of truly desperation.

You can write a custom Converter:

public class JsonCommentConverter : JsonConverter
{
    private readonly string _comment;
    public JsonCommentConverter(string comment)
    {
        _comment = comment;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
        writer.WriteComment(_comment); // append comment
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType) => true;
    public override bool CanRead => false;
}

and use it in your classes as:

public class Person
{
    [JsonConverter(typeof(JsonCommentConverter), "Name of the person")]
    public string Name { get; set; }

    [JsonConverter(typeof(JsonCommentConverter), "Age of the person")]
    public int Age { get; set; }
}

Serializing your class

 var person = new Person { Name = "Jack", Age = 22 };
 var personAsJson = JsonConvert.SerializeObject(person, Formatting.Indented);

will create the following output:

{
    "Name": "Jack"/*Name of the person*/,
    "Age": 22/*Age of the person*/
}

Json.net will convert back this string into a Person class without a problem.

Tags:

C#

Json

Json.Net