DataContractJsonSerializer.ReadObject (stream stream): can I read multiple objects?

I am working with .NET 4.0, VS 2010.

I am writing the file like this:

DataContractJsonSerializer btlSerializer = new DataContractJsonSerializer(typeof(BrainTrackList));
FileStream fs = File.OpenWrite(m_fileName);
btlSerializer.WriteObject(fs, trackList);

DataContractJsonSerializer npcemSerializer = new DataContractJsonSerializer(typeof(NPCExistsModelData));
npcemSerializer.WriteObject(fs, npcemData);

fs.Close();
fs.Dispose();

      

Which seems to give the result in a text file that I am expecting.

I'm trying to read it with this:

DataContractJsonSerializer btlSerializer = new DataContractJsonSerializer(typeof(BrainTrackList));
BrainTrackList listContainer = (BrainTrackList)btlSerializer.ReadObject(m_stream);

DataContractJsonSerializer npcemSerializer = new DataContractJsonSerializer(typeof(NPCExistsModelData));
NPCExistsModelData npceDataContainer = (NPCExistsModelData)npcemSerializer.ReadObject(m_stream);

      

where m_stream is a previously opened Stream object. The BtlSerializer returns the object I expect without issue, but then m_stream.Position is set to the end of the file and I cannot read the next object. I get the error "Waiting for element" root "from namespace ..."

Am I doing something wrong or do I just need to create an aggregate object for serialization containing both objects? I checked the MSDN documentation on ReadObject to see what it says about its effect on the Stream object, but this page has no information on the meaning.

+3


source to share


2 answers


Ok, this is weird, but apparently I just need to set the stream position back to the beginning before each call to ReadObject. It's smart enough to ignore everything in the file except for the type of object I'm trying to read.

So this works:



DataContractJsonSerializer btlSerializer = new DataContractJsonSerializer(typeof(BrainTrackList));
BrainTrackList listContainer = (BrainTrackList)btlSerializer.ReadObject(m_stream);

m_stream.Position = 0;

DataContractJsonSerializer npcemSerializer = new DataContractJsonSerializer(typeof(NPCExistsModelData));
NPCExistsModelData npceDataContainer = (NPCExistsModelData)npcemSerializer.ReadObject(m_stream);

      

+6


source


My problem was that I was using a StreamWriter object and needed to be cleaned up.

var ser = new DataContractJsonSerializer(typeof(Control[]));
using (var stream = new MemoryStream())
{
    var sw = new StreamWriter(stream);
    sw.Write(data);

      



sw.Flush ();

    stream.Position = 0;
    var pfControls = (Control[])ser.ReadObject(stream);
}

      

0


source







All Articles