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.
Can I add a comment in JSON? No, JSON is a data-only format. Comments in the form //, #, or /* */, which are used in popular programming languages, are not allowed in JSON. You can add comments to JSON as custom JSON elements that will hold your comments, but these elements will still be data.
Open the JSON file in your text editor and add comments the same way you would in Python (using # and not docstrings) or the same way you would in JavaScript (using // and not multi-line comments using /** */ ).
Newtonsoft. Json allows comments and trailing commas by default.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With