custom serializer for just one property in Json.NET

前端 未结 3 1618
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 10:17

UPDATE Found the issue -- was inheriting from wrong class, needed to be JsonConverter.

I have a class that has a Location property of type System.Da

3条回答
  •  独厮守ぢ
    2020-12-05 10:47

    You can add a custom serializer to a single attribute like this:

    public class Comment
    {
        public string Author { get; set; }
    
        [JsonConverter(typeof(NiceDateConverter))]
        public DateTime Date { get; set; }
    
        public string Text { get; set; }
    }
    
    public class NiceDateConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var date = value as DateTime;
            var niceLookingDate = date.ToString("MMMM dd, yyyy 'at' H:mm tt");
            writer.WriteValue(niceLookingDate);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }
    
        public override bool CanRead
        {
            get { return false; }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }
    }
    

    Then, when you serialize your object with JsonConvert.SerializeObject(), the custom serializer will be used for the Date property.

提交回复
热议问题