How to create a JSON.NET Date to String custom Converter

后端 未结 2 625
悲哀的现实
悲哀的现实 2020-12-01 16:03

Could someone tell me please how I can create a custom converter

I know I can use JSON.NET ISODateConvertor, but what I want is specific, I just want to send the va

相关标签:
2条回答
  • 2020-12-01 16:26

    If you are using Web Api add the custom formatter to the configuration using:

    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor())
    
    0 讨论(0)
  • 2020-12-01 16:45

    Something like this?

    string str = JsonConvert.SerializeObject(new DateTimeClass(), new MyDateTimeConvertor());
    
    public class DateTimeClass
    {
        public DateTime dt;
        public int dummy = 0;
    }
    
    public class MyDateTimeConvertor : DateTimeConverterBase
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return DateTime.Parse(reader.Value.ToString());
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );
        }
    }
    
    0 讨论(0)
提交回复
热议问题