This project has moved. For the latest updates, please go here.


Deserialization of Regex objects will fail with FormatException, when a StringEnumConverter is used for serialization


EDIT: The report originally referred to RegexConverter as the culprit of the bug, which is wrong. Apparently I am too dumb to read the StackTrace of the exception... :(


Deserialization of Json-serialized Regex objects fails with a FormatException, when a StringEnumConverter has been used during serialization.

Medium; the bug causes the deserialization of any Json data to fail fatally, if it contains Regex object data which had been generated by a serializer using a StringEnumConverter. However, writing your own JsonConverter for Regex objects can mitigate the problem.

Json.NET version:
5.0.4 (earlier versions are most likely affected as well).

Full description

Json-serialization and -deserialization of Regex objects work fine, if the serializer does not use a StringEnumConverter. In this case, Regex objects would serialize into Json such as:
{ "pattern": "\\s+[a-z]+", "options": 0 }
Adding a StringEnumConverter to the serializer will lead to the Options property of Regex objects being serialized as a string -- in this example "None" -- instead of a number (as one would expect).
{ "pattern": "\\s+[a-z]+", "options": "None" }
But such a serialized Regex object cannot be deserialized again by Json.NET, regardless whether a StringEnumConverter is added to the (de)serializer or not.

Cause of bug

(EDITED) The exception is thrown by the Int32 conversion of JsonFormatterConverter. The deserialization involving JsonFormatterConverter depends on .NET's Runtime.Serialization process. And somewhere during that process it is decided that the serialized data of property RegexOptions is Int32. I am not sure, whether Json.NET has a say in this, or whether this is handled entirely by .NET's serialization implementation.

Possible workaround

Implementation of a JsonConverter for Regex objects (and thus not relying on RegexConverter).
Closed May 4, 2013 at 4:11 AM by JamesNK
I've made RegexConverter the default way to serialize/deserialize regexes.