Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect on an ExpandoObject

I have written a nifty function that will accept a system.object, reflect on its properties and serialize the object into a JSON string. It looks like this:

public class JSONSerializer
{

    public string Serialize(object obj)

Now, I want to be able to do this to serialize a dynamic/ExpandoObject, but because my serializer uses reflection, it isn't able to do it. What's the workaround?

public class Test
{
    public dynamic MakeDynamicCat()
    {
        dynamic newCat = new ExpandoObject();
        newCat.Name = "Polly";
        newCat.Pedigree = new ExpandoObject();
        newCat.Pedigree.Breed = "Whatever";

        return newCat;
    }

    public void SerializeCat()
    {
        new JSONSerializer().Serialize(MakeDynamicCat());
    }
}
like image 233
Water Cooler v2 Avatar asked Jun 09 '10 10:06

Water Cooler v2


People also ask

What is an expandoObject?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.

How do I know if my expandoObject is empty?

You can use this to see if a member is defined: var expandoObject = ...; if(((IDictionary<String, object>)expandoObject). ContainsKey("SomeMember")) { // expandoObject. SomeMember exists. }


1 Answers

I think, this question is very similar: How do I reflect over the members of dynamic object?

At least the answers should help you too.

like image 110
Alexandra Rusina Avatar answered Oct 02 '22 08:10

Alexandra Rusina