How to serialize static or const member variables using JSON.NET?(如何使用 JSON.NET 序列化静态或常量成员变量?)
问题描述
我无法在任何地方找到答案,但是当我尝试使用静态或 const 成员变量序列化结构或类时,默认情况下它们不会序列化.如果我尝试通过设置 MemberSerialization.OptIn
来强制序列化,则会收到错误消息.
I haven't been able to find the answer to this anywhere, but when I try to serialize a struct or class with static or const member variables, they don't serialize by default. If I try to force serialization by setting MemberSerialization.OptIn
, I get an error.
例如
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty]
public int x = 1;
[JsonProperty]
public static int y = 2;
}
如果我尝试用以下方式序列化这个类:
If I try to serialize this class with:
Test t = new Test();
string s = JsonConvert.SerializeObject( t );
我收到错误Error getting value from 'y' on 'Test'
.如果 y 是 const,也会发生同样的情况.
I get the error Error getting value from 'y' on 'Test'
. The same happens if y is const.
我的理论是 static 和 const 值存储在内存中的某个特殊位置,并且由于某种原因,Json 序列化程序在尝试访问它们时会死掉.不过这完全是一种预感,我在 C# 参考中看不到任何内容对于静态,这是有帮助的.我对 C# 比较陌生 - 目前这确实是一个好奇的问题.
My theory is that static and const values are stored somewhere special in memory, and for some reason the Json serializer dies trying to access them. That's entirely a hunch though, and I see nothing in the C# Reference for Static that's of any help. I'm relatively new to C# - and this is really a curiosity question more than anything at this point.
推荐答案
如果它愿意,它当然可以序列化静态变量.序列化是通过使用反射 API 检查对象和类型来完成的,这些 API 允许您做任何事情"——这些值无法序列化没有技术原因.
It could certainly serialize the static variable if it wanted to. Serialization is done by inspecting objects and types with the Reflection APIs, and those APIs allow you to do "anything" -- there is no technical reason these values cannot be serialized.
但是,默认情况下不支持此功能有一个合乎逻辑的理由:它没有多大意义.您正在序列化一个 instance,而 static
或 const
成员在逻辑上不是实例的一部分,而是整个类的一部分.
There is, however, a logical reason not to support this by default: it doesn't make much sense. You are serializing an instance, and static
or const
members are not logically part of an instance but of the class as a whole.
也就是说,你仍然可以序列化 static
成员,如果它是一个属性:
That said, you can still serialize static
member if it's a property:
[JsonProperty]
public static int y { get; set; } // this will be serialized
当然,您可以通过创建自定义 JsonConverter
来完全覆盖序列化程序的行为.
And of course you can completely override the serializer's behavior by creating a custom JsonConverter
.
这篇关于如何使用 JSON.NET 序列化静态或常量成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 JSON.NET 序列化静态或常量成员变量?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01