Deserializing Noda Time LocalDateTime using JSON.NET

I am trying to use Json.NET to serialize some Noda time values ​​and issues. Serialization is quite simple:

LocalDateTime dt = ... // Assigned elsewhere LocalDateTimePattern isoDateTimePattern = LocalDateTimePattern.GeneralIsoPattern; JObject root = new JObject(); root.Add("time", isoDateTimePattern.Format(dt)); // Serialize other elements using (var sw = new StreamWriter(stream)) { serializer.Serialize(sw, root); } 

But deserialization is problematic. Json.NET seems to recognize the date and time formatted in ISO from the top and automatically convert it to a DateTime object, which is not what I want.

 using (var sr = new StreamReader(stream)) { using (var jr = new JsonTextReader(sr)) { var root = serializer.Deserialize<JObject>(jr); // Deserialize other elements var time = root.GetValue("time"); // time.Type is JTokenType.Date string timeStr = time.Value<string>(); // Is "01/10/2014 10:37:32" // Kaboom. String is not in the right format (see above comment) var parsedTime = isoDateTimePattern.Parse(time.Value<string>()); } } 

From the fact that timeStr comes out as a date and time in US format, I would suggest that time.Value<string>() just calls ToString on some internal DateTime object that Json.NET has already parsed. I could do something like

 var cdt = time.Value<DateTime>(); LocalDateTime ldt = new LocalDateTime(cdt.Year, cdt.Month, cdt.Day, cdt.Hour, cdt.Minute); 

but this is collapsed and means that Json.NET is performing unnecessary conversions.

Is there a way to get only the string value of a JSON value?

+7
date c # datetime nodatime
source share
1 answer

There is the NodaTime.Serialization.JsonNet package available on NuGet, which seems to target this particular situation. Here's how to set it up:

After downloading and installing the package in your solution, add the following using statement to the code:

 using NodaTime.Serialization.JsonNet; 

Set up your serializer as follows:

 JsonSerializer serializer = new JsonSerializer(); serializer.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 

Then, when you do deserialization, you can get LocalDateTime from JObject using ToObject<LocalDateTime>(serializer) as follows:

 using (var sr = new StreamReader(stream)) { using (var jr = new JsonTextReader(sr)) { var root = serializer.Deserialize<JObject>(jr); // Deserialize other elements var time = root.GetValue("time"); var parsedTime = time.ToObject<LocalDateTime>(serializer); } } 
+12
source share

All Articles