runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Exception when serialize class contains Dictionary and DateTimeOffset via DataContractSerializer

Open shmao opened this issue 9 years ago • 4 comments

@jiemon commented on Fri Aug 04 2017

I try serialize via DataContractSerializer simple class by example:

public class SimpleExampleClass2
		{
			private Dictionary<string, string> _attributes1;
			public Dictionary<string, string> Attributes1 => _attributes1;
			public DateTimeOffset TestDate { get; set; }
		}

Serialization code:

var test = new SimpleExampleClass2() { TestDate = DateTimeOffset.Now };
			var ser = new DataContractSerializer(typeof(SimpleExampleClass2));
			MemoryStream memoryStream = new MemoryStream();
			ser.WriteObject(memoryStream, test);
			memoryStream.Seek(0, SeekOrigin.Begin);
			return File(memoryStream, "application/xml", $"test.xml");

But on line "ser.WriteObject(memoryStream, test)" I get exception:

InvalidDataContractException: Type 'System.Runtime.Serialization.DateTimeOffsetAdapter' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

Is this bug in DataContractSerializer?


@Petermarcu commented on Fri Aug 04 2017

@zhenlan @ViktorHofer @danmosemsft


@ViktorHofer commented on Fri Aug 04 2017

It's not related to binary serialization with BinaryFormatter.


@Petermarcu commented on Fri Aug 04 2017

@zhenlan Any thoughts?


@zhenlan commented on Fri Aug 04 2017

  • @shmao

shmao avatar Aug 04 '17 17:08 shmao

I tried the repro code. The issues reproduces on both desktop and .Net Core. @jiemon, did you get the issue on .Net full Framework or on .Net Core?

shmao avatar Aug 04 '17 17:08 shmao

@jiemon can you try to modify your test class as shown below and see if it would work for you

                public class SimpleExampleClass2
		{
			private Dictionary<string, string> _attributes1 = new Dictionary<string, string>();
			public Dictionary<string, string> Attributes1 => _attributes1;
			public DateTimeOffset TestDate { get; set; }
		}

shmao avatar Aug 04 '17 19:08 shmao

yes it works properly

jiemon avatar Aug 04 '17 21:08 jiemon

Thanks for the confirmation, @jiemon . The property Attributes1 is a get-only collection. To be able to serialize a type with get-only collection property, DataContractSerializer requires the property to be initialized either in the constructor of the type or in the property's getter. As long as the property is initialized, the serialization should work fine.

With that said, the error message here is wrong, which is caused by a bug in DataContractSerializer. We would consider to fix it.

shmao avatar Aug 04 '17 23:08 shmao