如何为Json.NET输出添加注释?

Ada*_*ger 19 c# json json.net

有没有办法可以自动添加注释到JSON.Net的序列化输出?

理想情况下,我认为它类似于以下内容:

public class MyClass 
{
    [JsonComment("My documentation string")]
    public string MyString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

或者(如果可以避免注释,则更好):

public class MyClass 
{
    /// <summary>
    /// My documentation string
    /// </summary>
    public string MyString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

会产生:

{ 
    //My documentation string
    "MyString": "Test"
}
Run Code Online (Sandbox Code Playgroud)

我问的原因是我们使用Json.NET来序列化配置文件,以后可以手动更改.我想在我的C#配置类中包含文档,并在JSON中重现这些文档,以帮助以后可能需要更改文件的人.

更新:正如RoToRa在下面指出的那样,在JSON规范中技术上不允许发表评论(请参阅http://www.json.org上方便的语法图).但是,Json.NET站点上的功能表包括:

支持阅读和撰写评论

Newtonsoft.Json.JsonTextWriter.WriteComment(string)存在输出评论.我对创建注释的简洁方法感兴趣,而不是JsonTextWriter直接使用.

RoT*_*oRa 5

问题是JSON作为文件格式不支持注释。您可以做的一件事-如果读取JSON文件的应用程序允许它-按照此问题的建议使用其他属性作为注释:注释可以在JSON中使用吗?


Jam*_*ing 5

序列化时,Json.NET JsonSerializer不会自动输出注释.如果你想要评论,你需要手动编写你的JSON,使用JsonTextWriter或LINQ to JSON

  • @JamesNewtonKing我已经为最新的Json.NET编写了一个小补丁,将`Comment`属性添加到`JsonProperty`(和`JsonPropertyAttribute`).我们的想法是,在`SerializeMemberInfo`期间,如果`Comment`不为null/empty,那么它将被写出JSON中的键/值对之上.在我继续完成之前,你会感兴趣的是什么? (6认同)
  • 我会看看它,看看你是如何做到的,以及我是否认为它对其他人有用 - http://json.codeplex.com/SourceControl/list/patches/upload (3认同)
  • @JamesNewton-King有什么事吗? (3认同)
  • @AdamRodger你还有补丁吗?我在网上找不到它. (2认同)

Chr*_*all 5

好吧,为了在输出中添加注释,人们可以做一些事情,但除非出于真正的绝望,否则我不会这样做。

您可以编写自定义转换器:

public class JsonCommentConverter : JsonConverter
{
    private readonly string _comment;
    public JsonCommentConverter(string comment)
    {
        _comment = comment;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
        writer.WriteComment(_comment); // append comment
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType) => true;
    public override bool CanRead => false;
}
Run Code Online (Sandbox Code Playgroud)

并在你的类中使用它:

public class Person
{
    [JsonConverter(typeof(JsonCommentConverter), "Name of the person")]
    public string Name { get; set; }

    [JsonConverter(typeof(JsonCommentConverter), "Age of the person")]
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

序列化你的类

 var person = new Person { Name = "Jack", Age = 22 };
 var personAsJson = JsonConvert.SerializeObject(person, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

将创建以下输出:

{
    "Name": "Jack"/*Name of the person*/,
    "Age": 22/*Age of the person*/
}
Run Code Online (Sandbox Code Playgroud)

PersonJson.net 会毫无问题地将这个字符串转换回一个类。