有没有办法可以自动添加注释到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直接使用.
序列化时,Json.NET JsonSerializer不会自动输出注释.如果你想要评论,你需要手动编写你的JSON,使用JsonTextWriter或LINQ to JSON
好吧,为了在输出中添加注释,人们可以做一些事情,但除非出于真正的绝望,否则我不会这样做。
您可以编写自定义转换器:
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 会毫无问题地将这个字符串转换回一个类。
| 归档时间: |
|
| 查看次数: |
5805 次 |
| 最近记录: |