Open floyd-may opened 5 years ago
Some additional context:
I spent some time looking through the source code to see if a hook existed to do what I wanted. That search led me to here: https://github.com/JamesNK/Newtonsoft.Json/blob/d48558b53b0a516bfa15c1af50231ea1ba7c2454/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs#L518-L524
The memberContract
variable gets set to the contract corresponding to the run-time type of the property's value unless the property type happens to be sealed. There doesn't appear to be a way to override this behavior hence the hackish workaround above.
I agree this would be useful. Without it, it's impossible to serialize things like COM objects accurately, all of which have an identical, opaque runtime representation. The only way to correctly serialize these values is in via type directed serialization.
I'd like to be able to serialize according to the declared property type rather than the concrete type at runtime.
Source/destination types
Expected behavior
I would like to be able to easily configure the serializer to do this:
Actual behavior
This is how a message would get serialized by default given the above types.
Workaround
This workaround makes some pretty egregious assumptions. If you expect that the entirety of
Message
and not justIMessage
to get serialized in any scenario, this will do The Wrong Thing (tm).Proposal
I believe that the core of the issue is that the
IContractResolver
interface has no knowledge of what the declared property type is. I would humbly suggest adding an additionalType
parameter containing the declared type so that the resolver can make the determination of what contract to resolve. Given the above types, I would love to be able to write a custom contract resolver that looks like this: