How do I add comments to Json.NET output?
c#, json, json.net
Solution
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
Problem
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.