0

I am trying to do a custom Datetime jsonconverter, I am trying to get the json string inside the ReadJson but it seems the value gets converted to Datetime before it gets passed to ReadJson. currently, I get the value like Start: 11/27/2020 05:42:00 however I need it to be exactly as the input json Start: "2020-11-27T16:42:00.000+11:00

https://dotnetfiddle.net/6Oe2D7

class Program
    {
        static void Main(string[] args)
        {
            string json = @"{ ""Start"": ""2020-11-27T16:42:00.000+11:00""}";
            Absense parsed = JsonConvert.DeserializeObject<Absense>(json);
        }
    }
    class Absense
    {
        [Newtonsoft.Json.JsonConverter(typeof(DatetimeJsonConverter))]
        public DateTime Start { get; set; }
    }

    class DatetimeJsonConverter : JsonConverter<DateTime?>
    {
        public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            string value = reader.Value?.ToString();
            Console.WriteLine($"{reader.Path}: {value}"); //I want the value here to be exactly as the input json
            if (value != null)
            {
                if (DateTimeOffset.TryParse(value, out DateTimeOffset timeOffset))
                {
                    return new DateTime(timeOffset.Year, timeOffset.Month, timeOffset.Day, timeOffset.Hour, timeOffset.Minute, timeOffset.Second);
                }
            }

            return existingValue;
        }

        public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
        {
            if (value.HasValue)
            {
                writer.WriteValue(value.Value.ToString("s", System.Globalization.CultureInfo.InvariantCulture));
            }
            else
            {
                writer.WriteNull();
            }
        }
    }
  • Because JSON has no primitive for `DateTime`, Json.NET has built-in logic to automatically recognize and deserialize strings that look like dates and times in the parser. For you converter to work, you need to disable automatic recognition by setting [`DateParseHandling.None`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateParseHandling.htm). – dbc Nov 27 '20 at 14:17
  • To do that see [json.net: DateTimeStringConverter gets an already DateTime converted object in ReadJson()](https://stackoverflow.com/q/53508910/3744182) via settings or [How to prevent a single object property from being converted to a DateTime when it is a string](https://stackoverflow.com/a/40644970/3744182) (via a converter on the parent). – dbc Nov 27 '20 at 14:17

0 Answers0