Why Does (De)Serialization Fails When JsonConverter.CanConvert(Type) returns false? #49345
Unanswered
roy-cohen273
asked this question in
Ideas
Replies: 1 comment 6 replies
-
If you annotate the converter on a type or a member, the it's intended to support the thing it's annotated to. |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When applying
[JsonConverter(typeof(MyJsonConverter))]
to a type, (de)serialization fails ifMyJsonConverter.CanConvert
returns false. Why dosn't the (de)serialization continue on as ifMyJsonConverter
didn't exist, i.e. use the default (de)serialization?Example:
I would like the output of this program to be
{"Name": "<some name>"}
but instead I get an error:Unhandled exception. System.InvalidOperationException: The converter specified on 'JsonOptionConverter.SimplePoco' is not compatible with the type 'JsonOptionConverter.SimplePoco'.
.Why is this like that? Why not ignore a converter if that converter's
CanConvert
method returns false? To avoid changing code that's already written, this behaviour can be activated only when a property on theJsonConverter
istrue
(like theHandleNull
property).I've looked at the source code and I don't think that would be hard to implement (if people even want this). I think all it takes is adding
public virtual bool Optional { get; } = false;
inJsonConverter
, and changing a little bit the private functionJsonSerializerOptions.GetConverterFromAttribute
in JsonSerializerOptions.Converters.cs line 321:This is my first time starting a discussion so please tell me if I'm doing something wrong.
Should this have been filed as an issue instead?
Edit: I added more elaboration about specific code changes.
Edit: After some more reading I noticied such a change will fall under bucket 2 of breaking changes:
I don't see a reason why you would serialize a
JsonConverter
but I thought I mentioned it anyway.Beta Was this translation helpful? Give feedback.
All reactions