如何向Json.NET输出添加注释? [英] How do I add comments to Json.NET output?

查看:685
本文介绍了如何向Json.NET输出添加注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



理想情况下,我会想像这是类似于以下内容: p>

  public class MyClass 
{
[JsonComment(我的文档字符串)]
public string MyString {get;组; }
}

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

  public class MyClass 
{
///< summary>
///我的文档字符串
///< / summary>
public string MyString {get;组;
}

将产生:

  {
//我的文档字符串
MyString:测试
}

我问的原因是我们使用Json.NET序列化一个配置文件,稍后可以手动更改。我想在我的C#配置类中添加文档,并在JSON中转载,以帮助谁可能稍后更改文件。



更新:正如RoToRa所指出的那样,JSON规范中的技术上不允许使用注释(请参阅 http:/ /www.json.org )。但是, Json.NET站点上的功能表包括:


支持阅读和撰写评论


和<$ c $存在输出注释的c> Newtonsoft.Json.JsonTextWriter.WriteComment(string)。我有兴趣创建评论,而不是直接使用 JsonTextWriter

解决方案

当序列化时,Json.NET JsonSerializer不会自动输出注释。您需要手动编写JSON,如果您需要评论,可以使用JsonTextWriter或LINQ to JSON $ /

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

这篇关于如何向Json.NET输出添加注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆