23

Is there a way I can automatically add comments to the serialised output from Json.NET?

Ideally, I'd imagine it's something similar to the following:

public class MyClass
{
    [JsonComment("My documentation string")]
    public string MyString { get; set; }
}

Or (even better if annotations can be avoided):

public class MyClass
{
    /// <summary>
    /// My documentation string
    /// </summary>
    public string MyString { get; set; }
}

Tthat would produce:

{
    // My documentation string
    "MyString": "Test"
}

The reason that I ask is that we use Json.NET to serialise a configuration file which could be changed by hand later on. I'd like to include documentation in my C# configuration classes and have that reproduced in the JSON to help whoever may have to change the file later.


As RoToRa points out below, comments are not technically allowed in the JSON specification (see the handy syntax diagrams at http://www.json.org). However, the features table on the Json.NET site includes:

Supports reading and writing comments

and Newtonsoft.Json.JsonTextWriter.WriteComment(string) exists which does output a comment. I'm interested in a neat way of creating the comments rather than using the JsonTextWriter directly.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Rodger
  • 3,472
  • 4
  • 33
  • 45

4 Answers4

8

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

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • 7
    @JamesNewtonKing I've written a small patch to the latest Json.NET to add a `Comment` property to `JsonProperty` (and `JsonPropertyAttribute`). The idea is that during `SerializeMemberInfo` if the `Comment` is not null/empty then it gets written out above the key/value pair in the JSON. Before I go on and complete it, is that something you'd be interested in? – Adam Rodger Mar 01 '12 at 08:25
  • 3
    I'll take a look at it and see how you've done it and whether I think it would be useful to others - http://json.codeplex.com/SourceControl/list/patches/upload – James Newton-King Mar 01 '12 at 22:03
  • 3
    @AdamRodger do you still have the patch? I can't find it online. – nikeee Aug 03 '15 at 22:54
  • 7
    @JamesNewton-King Did anything ever come of this? – Basic Dec 14 '15 at 21:28
  • @JamesNewton-King also interested in this. – MrHinsh - Martin Hinshelwood Dec 17 '20 at 11:22
5

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?

Community
  • 1
  • 1
RoToRa
  • 37,635
  • 12
  • 69
  • 105
4

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.

ChristianMurschall
  • 1,621
  • 15
  • 26
3

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"
    } 
}
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268