C# How to serialize (JSON, XML) normal properties on a class that inherits from 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的类的普通属性


- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01