0

I am trying to serialize and deserialize a object using DataContractSerializer. While doing the deserialization i.e. executing readObject function over stream data, I am facing error with exception message

There was an error deserializing the object of type. The data at the root level is invalid. Line 1, position 1

Here is the snippet of code I have used:

DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(**Object**));
dataContractSerializer.WriteObject(stream, **Object**);
// Do something
stream.seek(0, SeekOrigin.begin);
dataContractSerializer.ReadObject(stream);

I have gone through the similar error mentioned at xml.LoadData - Data at the root level is invalid. Line 1, position 1, but there we are working on string and I am not able to find length of BOM characters over stream.

Can someone provide a way out of this error?

  • We need to see a [mcve] to help you. But did you remember to reset the stream position to `0` before reading from it? See e.g. [DataContract framework not working when serializing objects to JSON](https://stackoverflow.com/a/44778481/3744182). – dbc Jun 24 '21 at 03:53
  • 1
    Yes, did that. And this is not reproducable everytime. –  Jun 24 '21 at 04:09
  • Then we need to see code that reproduces the problem at least some time. The full `ToString()` output of the exception including the exception type, message, traceback and inner exception(s) might help also. – dbc Jun 24 '21 at 04:16
  • Often this is due when there are white spaces at beginning of the xml and the simple solution is to remove the white characters. XML expects the open angle bracket to be the first character. Also file should be UTF-8. You can try opening file with notepad and then SAVE AS and in bottom of GUI change type to UTF-8. If first line of XML is not UTF-8 (UTF-16) the Net library doesn't like the first line and you can skip in code by using Readline() method. – jdweng Jun 24 '21 at 07:23

0 Answers0