How do I add comments to Json.NET output?

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; }
}

that 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.

Update : As RoToRa points out below, comments are not technically allowed in the JSON spec (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.


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"
    } 
}
链接地址: http://www.djcxy.com/p/3404.html

上一篇: 解决JSONException重复键

下一篇: 如何添加评论到Json.NET输出?