Reflect on an ExpandoObject

三世轮回 提交于 2019-12-07 03:57:29

问题


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());
    }
}

回答1:


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.




回答2:


I would suggest to use JSON.NET to serialize. The version 3.5 supports serializing dynamic objects (like expando). Deserialization from JSON to dynamic object involves a little efforts but that too isn't too cumbersome. The below post lists that out:

Dynamic Object Serialization



来源:https://stackoverflow.com/questions/3004965/reflect-on-an-expandoobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!