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的类的普通属性


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01