6

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?

4

2 回答 2

4

您可以使用来自的 DataContract/DataMember 属性System.Runtime.Serialization

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

这样,无论您使用什么序列化器,序列化都将起作用......

于 2013-09-16T07:14:03.347 回答
3

只需使用JsonProperty属性

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

输出: {"MyNormalProperty":"Hello, world!"}

于 2013-09-16T07:08:17.367 回答