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的类的普通属性
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01