How do I add comments to Json.NET output?

删除回忆录丶 提交于 2019-12-05 10:07:22

问题


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.


回答1:


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




回答2:


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?




回答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"
    } 
}


来源:https://stackoverflow.com/questions/9495718/how-do-i-add-comments-to-json-net-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!