Is it possible to return an ExpandoObject from a web service call?

I would like to return ExpandoObject from WebMethod, for example:

[WebMethod]
public ExpandoObject TestMethod(int val)
{
     dynamic item = new ExpandoObject();

     item.Value = val;
     item.SomeOtherStuff = "SomeOtherStuff";

     DynamicallyAddMoreFields(item);

     return item;
}

      

When I try to do this, I get this error:

To be XML serializable, types that inherit from IEnumerable must have an Add (System.Object) implementation

And I cannot extend the ExpandoObject class as it is sealed.

Is there another way to do this?

+3


source to share


1 answer


You can create your own serializable version of ExpandoObject by inheriting from DynamicObject and implementing ISerializable .

ExpandoObject is basically a dictionary that stores the names of dynamically attached properties along with values:



[Serializable]
public class SerializableExpandoObject : DynamicObject, ISerializable
{
    private Dictionary<string, object> properties = new Dictionary<string, object>()

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return properties.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        properties.Add(binder.Name, value);
        return true;
    }

    ....
}

      

You can implement any serialization format you need to support here, including IXmlSerializable .

+7


source







All Articles