C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject

别来无恙 提交于 2019-11-27 07:55:08

问题


I am trying to serialize an instance of a class that inherits from DynamicObject. I've had no trouble getting the dynamic properties to serialize (not demonstrated here for brevity), but "normal" properties don't seem to make the trip. I experience the same problem regardless of serialization class: it's the same for JavaScriptSerializer, JsonConvert, and XmlSerializer.

public class MyDynamicClass : DynamicObject
{
    public string MyNormalProperty { get; set; }
}

...

MyDynamicClass instance = new MyDynamicClass()
{
    MyNormalProperty = "Hello, world!"
};

string json = JsonConvert.SerializeObject(instance);
// the resulting string is "{}", but I expected to see MyNormalProperty in there

Shouldn't MyNormalProperty show up in the serialized string? Is there a trick, or have I misunderstood something fundamental about inheriting from DynamicObject?


回答1:


You can use the DataContract/DataMember attributes from System.Runtime.Serialization

    [DataContract]
    public class MyDynamicClass : DynamicObject
    {
        [DataMember]
        public string MyNormalProperty { get; set; }
    }

This way the serialisation will work no matter what serialiser you use...




回答2:


Just use JsonProperty attribute

public class MyDynamicClass : DynamicObject
{
    [JsonProperty("MyNormalProperty")]
    public string MyNormalProperty { get; set; }
}

Output: {"MyNormalProperty":"Hello, world!"}



来源:https://stackoverflow.com/questions/18822121/c-sharp-how-to-serialize-json-xml-normal-properties-on-a-class-that-inherits

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