如何使用JSON.NET序列化静态或const成员变量? [英] How to serialize static or const member variables using 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 );
我收到错误从测试"的"y"获取值的错误
.如果y为常量,也会发生同样的情况.
I get the error Error getting value from 'y' on 'Test'
. The same happens if y is const.
我的理论是,静态和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.
推荐答案
如果愿意,它当然可以序列化静态变量.序列化是通过使用Reflection 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序列化静态或const成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!