How do I add comments to Json.NET output?

后端 未结 4 1560
攒了一身酷
攒了一身酷 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: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.

提交回复
热议问题