C#如何在从DynamicObject继承的类上序列化(JSON,XML)常规属性 [英] C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject

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

问题描述

我正在尝试序列化从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]
    public class MyDynamicClass : DynamicObject
    {
        [DataMember]
        public string MyNormalProperty { get; set; }
    }

这样,无论您使用哪种序列化程序,序列化都能正常工作...

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

这篇关于C#如何在从DynamicObject继承的类上序列化(JSON,XML)常规属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆