Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add comments to Json.NET output?

Tags:

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.

like image 222
Adam Rodger Avatar asked Feb 29 '12 08:02

Adam Rodger


People also ask

How do I put comments in a JSON file?

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.

How do I comment out a line in JSON file?

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 /** */ ).

Does Newtonsoft JSON support comments?

Newtonsoft. Json allows comments and trailing commas by default.

How do I deserialize JSON?

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.


1 Answers

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

like image 171
James Newton-King Avatar answered Oct 22 '22 12:10

James Newton-King