Repository navigation
Description
Description
If you use DataContractJsonSerializer with ExtensionDataObject and try to serialize data when extension data contains a nested complex object with the single property then the serializer throws an exception because the deserializer incorrectly decides that property of a nested object has the type of array but this assumption breaks serializer invariants.
Consider the following data contract:
[DataContract]
public class ContractGeneric : IExtensibleDataObject
{
public ExtensionDataObject ExtensionData { get; set; }
}If you try to deserialize JSON {"item":{"id":0}} to the type ContractGeneric and after that immediately serialize this data back to JSON then you get the exception:
Unhandled exception. System.Runtime.Serialization.SerializationException:
There was an error serializing the object of type DataContractJsonSerializeExample.ContractGeneric.
Encountered unexpected element local name 'id' for item in collection. 'item' is the only valid local name for elements in a collection.
You can find a repository with the full example here: https://github.com/Umqra/DataContractJsonSerializeExample
Also, there is a docker image with a console application that reproduces the bug: https://hub.docker.com/r/sivukhin/data-contract-json-serializer-example
Configuration
Runtime: .NET 5.0 but problem also reproduced in netcoreapp2.0
Operation System: Windows
Architecture: x64
Problem
Probably the cause of the problem lies in the automatic type detection for ExtensionDataObject content, more precisely inconsistency in behaviour of deserializer for JSON may happen at the following line:
Line 969 in 57bfe47
| if (elementName != null && couldBeCollectionData) |
Here XmlObjectSerializerReadContext tries to determine type of element and in case when object contains only single property the algorithm decide that this is an array (which is wrong!).
Activity
sivukhin commentedon Jul 13, 2021
Should I mention someone to draw attention to the issue?
StephenMolloy commentedon Jul 31, 2021
Some more information. I can reproduce this exception on .Net 6, but not on .Net 4.8.
Align DCJS with 4.8 version. This work addresses dotnet#55270.
Align DCJS with 4.8 implementation. (#57533)
Align DCJS with 4.8 version. This work addresses #55270.
Align DCJS with 4.8 version. This work addresses #55270.
[release/6.0-rc1] Align DCJS with 4.8 implementation. (#57883)