How do I add comments to Json.NET output?

后端 未结 4 1573
攒了一身酷
攒了一身酷 2021-02-18 21:56

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:

pub         


        
相关标签:
4条回答
  • 2021-02-18 22:12

    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"
        } 
    }
    
    0 讨论(0)
  • 2021-02-18 22:16

    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

    0 讨论(0)
  • 2021-02-18 22:25

    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?

    0 讨论(0)
  • 2021-02-18 22:34

    Well there is something one can do in order to add a comment to the output, but I would not do it except out of truly desperation.

    You can write a custom Converter:

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

    and use it in your classes as:

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

    Serializing your class

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

    will create the following output:

    {
        "Name": "Jack"/*Name of the person*/,
        "Age": 22/*Age of the person*/
    }
    

    Json.net will convert back this string into a Person class without a problem.

    0 讨论(0)
提交回复
热议问题