C#如何序列化(JSON,XML)继承自DynamicObject的类的普通属性

C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject(C#如何序列化(JSON,XML)继承自DynamicObject的类的普通属性)

本文介绍了C#如何序列化(JSON,XML)继承自DynamicObject的类的普通属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化从 DynamicObject 继承的类的实例.我可以毫无困难地让动态属性序列化(为简洁起见,此处未演示),但正常"属性似乎并没有成功.无论序列化类如何,我都会遇到同样的问题:JavaScriptSerializer、JsonConvert 和 XmlSerializer 都是一样的.

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

MyNormalProperty 不应该出现在序列化字符串中吗?有什么技巧,还是我误解了从 DynamicObject 继承的一些基本知识?

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

推荐答案

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

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

这样,无论你使用什么序列化器,序列化都可以工作......

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

这篇关于C#如何序列化(JSON,XML)继承自DynamicObject的类的普通属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C#如何序列化(JSON,XML)继承自DynamicObject的类的普通属性

基础教程推荐