question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

String is converted as DateTime when deserializing Dictionary<string, string>

See original GitHub issue

I am trying to deserialize string as Dictionary<string, string>, but when string with ISO datetime is passed as value of some dictionary key, it is converted to datetime

Source/destination types

Dictionary<string, string>

Source/destination JSON

{"date":"2018-03-01T00:00:01Z"}

Expected behavior

the value of “date” key when deserialized to Dictionary<string, string> is “2018-03-01T00:00:01Z”

Actual behavior

the value of “date” key is “03/01/2018 00:00:01”

Steps to reproduce

		[Test]
		public void StringDateTimeSerializationTest()
		{
			var serializationSettings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Objects,
				ContractResolver = new CamelCasePropertyNamesContractResolver(),
				MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
			};

			serializationSettings.Converters.Add(new StringEnumConverter());

			serializationSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss" });

			var dateStr = "2018-03-01T00:00:01Z";

			var dictionaryStr = $"{{\"date\": \"{dateStr}\"}}";

			var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(dictionaryStr, serializationSettings);

			Console.WriteLine(dictionary["date"]);

			Assert.AreEqual(dateStr, dictionary["date"]);
		}

result: Message: Expected string length 20 but was 19. Strings differ at index 0. Expected: “2018-03-01T00:00:01Z” But was: “03/01/2018 00:00:01”

Is there a way to disable converting in this scenario (when is deserializing to Dictionary<string, string>)?

I tried to implement a custom converter, but the Value of JsonReader is already converted there

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:14
  • Comments:9

github_iconTop GitHub Comments

2reactions
parawanderercommented, Apr 25, 2022

@bo55vxr Unless I am mistaken, this is the same problem as described in https://github.com/JamesNK/Newtonsoft.Json/issues/862 I believe the author does not intend to fix this behaviour as it is considered to be “by design”. The potential solutions are changing the configuration in ways reported in that thread.

1reaction
bo55vxrcommented, Apr 26, 2022

@parawanderer After further investigations, I added DateParseHandling = DateParseHandling.None to the JsonSerializerSettings object which resolved the issue.

@bo55vxr : I used a similar workaround for my problem, but it makes our developers have to know that they need to set the settings on the serializer when the class in question has one or more properties that are dressed with the JsonConverterAttribute with our custom converter. This is problematic as the whole point of the custom converter is to handle the Dates the way we want to, not the default.

That said, it would be nice if the Converter could override the DateParseHandling setting so the converter can fully handle the date in the way we need it to. I apologize if I’m not articulating it well; I hope it makes sense what our use case is.

@jlitster For me it was actually a simple process as the Newtonsoft package encapsulated in a custom class, specifically to abstract our code from any one vendor (in fact I do this for most 3rd party packages). If we want to switch from Newtonsoft to another, we only have to change our encapsulation class.

So in this case, I just added the setting into the exposed deserialization methods with an optional boolean method argument to indicate if DateParseHandling.None handling was required, or to use the default (which is DateParseHandling.DateTime)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Newtonsoft Json converts datetime format when ...
So here is what I'm doing as a workaround. First, I moved the date/time format string to a public constant: public const string...
Read more >
How to serialize and deserialize JSON using C# - .NET
To write JSON to a string or to a file, call the JsonSerializer.Serialize method. The following example creates JSON as a string: C#...
Read more >
How to write custom converters for JSON serialization - .NET
The Main method deserializes a JSON string into a WeatherForecast instance, first without using the converter, and then using the converter. ...
Read more >
C# How to serialize/deserialize an Object to/from ...
I would want to put the JSON serialized string directly into the document properties, not on a sub-level. What are the downsides of...
Read more >
Custom Dictionary JsonConverter using System.Text.Json
We need to customize the deserialization of Dictionary<string, object>. We will do this by creating a custom JsonConverter.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found