Error converting to DateTime

jrahma 111 Reputation points
2021-01-24T17:58:53.077+00:00

Hi,

i am getting a date from MySQL with System.Text.Json and this is my output:

[{"time_to_activate":"2020-01-24 10:30:00"}]

this is my class:

class TimeToActivateDetails
{
    public DateTime time_to_activate { get; set; }
}

then:

List<TimeToActivateDetails> data = JsonSerializer.Deserialize<List<TimeToActivateDetails>>(result);

DateTime current_time = data[0].time_to_activate.ToLocalTime();

await App.Current.MainPage.DisplayAlert("current_time", Convert.ToString(current_time), "Ok");

but I am getting this error:

System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $[0].time_to_activate | LineNumber: 0 | BytePositionInLine: 42. ---> System.FormatException: The JSON value is not in a supported DateTime format.
at System.Text.Json.Utf8JsonReader.GetDateTime () [0x00010] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.Serialization.Converters.DateTimeConverter.Read (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) [0x00000] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.JsonPropertyInfo1[T].ReadJsonAndSetMember (System.Object obj, System.Text.Json.ReadStack& state, System.Text.Json.Utf8JsonReader& reader) [0x000ae] in <7e3a59f5e4004edbb4b17c580799cc52>:0 at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1[T].ReadPropertyValue (System.Object obj, System.Text.Json.ReadStack& state, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.JsonPropertyInfo jsonPropertyInfo, System.Boolean useExtensionProperty) [0x0001b] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1[T].OnTryRead (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state, T& value) [0x0008e] in <7e3a59f5e4004edbb4b17c580799cc52>:0 at System.Text.Json.Serialization.JsonConverter1[T].TryRead (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state, T& value) [0x001a7] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter2[TCollection,TElement].OnTryRead (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state, TCollection& value) [0x0009d] in <7e3a59f5e4004edbb4b17c580799cc52>:0 at System.Text.Json.Serialization.JsonConverter1[T].TryRead (System.Text.Json.Utf8JsonReader& reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state, T& value) [0x001a7] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.Serialization.JsonConverter1[T].ReadCore (System.Text.Json.Utf8JsonReader& reader, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state) [0x000c7] in <7e3a59f5e4004edbb4b17c580799cc52>:0 --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ReThrowWithPath (System.Text.Json.ReadStack& state, System.Text.Json.Utf8JsonReader& reader, System.Exception ex) [0x00010] in <7e3a59f5e4004edbb4b17c580799cc52>:0 at System.Text.Json.Serialization.JsonConverter1[T].ReadCore (System.Text.Json.Utf8JsonReader& reader, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state) [0x0014b] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.JsonSerializer.ReadCore[TValue] (System.Text.Json.Serialization.JsonConverter jsonConverter, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state) [0x0000a] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.JsonSerializer.ReadCore[TValue] (System.Text.Json.Utf8JsonReader& reader, System.Type returnType, System.Text.Json.JsonSerializerOptions options) [0x00023] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.JsonSerializer.Deserialize[TValue] (System.String json, System.Type returnType, System.Text.Json.JsonSerializerOptions options) [0x0007a] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at System.Text.Json.JsonSerializer.Deserialize[TValue] (System.String json, System.Text.Json.JsonSerializerOptions options) [0x0000e] in <7e3a59f5e4004edbb4b17c580799cc52>:0
at Angels.Settings.PopupLayout_Opened (System.Object sender, System.EventArgs e) [0x00183] in /Users/jassim/Projects/Angels/Angels/Angels/Settings.xaml.cs:379
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/14.8.0.3/src/Xamarin.iOS/Foundation/NSAction.cs:178
at at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/14.8.0.3/src/Xamarin.iOS/UIKit/UIApplication.cs:86
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/14.8.0.3/src/Xamarin.iOS/UIKit/UIApplication.cs:65
at Angels.iOS.Application.Main (System.String[] args) [0x00001] in /Users/jassim/Projects/Angels/Angels/Angels.iOS/Main.cs:17

Kindly help..

Thanks,
Jassim

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ken Tucker 5,846 Reputation points
    2021-01-24T19:21:13.84+00:00

    You need to add an custom JsonConverter. You can read more about it in this article.

        public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>  
        {  
            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)  
            {  
                Debug.Assert(typeToConvert == typeof(DateTime));  
                return DateTime.Parse(reader.GetString());  
            }  
    
            public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)  
            {  
                writer.WriteStringValue(value.ToString());  
            }  
        }  
    

    Then you can deserialize like this

            JsonSerializerOptions options = new JsonSerializerOptions();  
            options.Converters.Add(new DateTimeConverterUsingDateTimeParse());  
    
            string json = "[{\"time_to_activate\":\"2020-01-24 10:30:00\"}]";  
            var result = System.Text.Json.JsonSerializer.Deserialize<List<TimeToActivateDetails>>(json, options);  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. jrahma 111 Reputation points
    2021-01-24T19:41:30.417+00:00

    I hope Microsoft will make it easier without Converters because if the data is a DATE type in the database and I am specifying it as DateTime in my class then why do I need to Converter!

    1 person found this answer helpful.
    0 comments No comments