I'm trying to use a System.Dynamic.ExpandoObject
so I can dynamically create properties at runtime. Later, I need to pass an instance of this object and the mechanism used requires serialization.
Of course, when I attempt to serialize my dynamic object, I get the exception:
System.Runtime.Serialization.SerializationException was unhandled.
Type 'System.Dynamic.ExpandoObject' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Can I serialize the ExpandoObject? Is there another approach to creating a dynamic object that is serializable? Perhaps using a DynamicObject wrapper?
I've created a very simple Windows Forms example to duplicate the error:
using System;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Dynamic;
namespace DynamicTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dynamic dynamicContext = new ExpandoObject();
dynamicContext.Greeting = "Hello";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, dynamicContext);
stream.Close();
}
}
}
Maybe a bit late to answer but I use jsonFx to serialize and deserialize expandoObjects and it works very well :
serialization:
deserialization
I can't serialize ExpandoObject, but I can manually serialize DynamicObject. So using the TryGetMember/TrySetMember methods of DynamicObject and implementing ISerializable, I can solve my problem which was really to serialize a dynamic object.
I've implemented the following in my simple test app:
and Why does SerializationInfo not have TryGetValue methods? had the missing puzzle piece to keep it simple.
ExpandoObject
implementsIDictionary<string, object>
, e.g.:You could write the contents of the dictionary to a file, and then create a new ExpandoObject through deserialisation, cast it back to a dictionary and write the properties back in?