Deserialize specific enum into system.enum in Json.Net(将特定枚举反序列化为 Json.Net 中的 system.enum)
问题描述
我有一个相当通用的规则"类,我用它来驱动我正在编写的分析引擎的行为:
RuleType 是一个特定的枚举,如下所示:
使用 Json.NET,序列化和反序列化都很好.
然而,RuleEnum 给我带来了问题.无论是使用默认枚举序列化还是字符串枚举序列化,都没有提供枚举的具体类型.因此,在反序列化期间,我只剩下 System.Enum 和一个字符串值,这完全没有帮助.
这是一个序列化的例子,来说明我在说什么:
在这种情况下,RuleFlagEnum 指的是枚举:
我已尝试使用 Json.NET 中的所有 TypeNameHandling 选项.他们只对对象进行类型提示,这对 RuleFlagEnum 没有帮助,因为它在技术上是一个原语.
我真的非常想将枚举保留在 System.Enum 中,这样我们就可以加载任意枚举,以便以后按规则类型进行解释,这样整个事情就更具可扩展性.这可能吗?
解决方案
这里的难点在于 System.Enum 是一个抽象类,因此不可能将未知具体类型的值反序列化为这种类型.相反,需要在 JSON 中的某处具有特定类型信息,但是 Json.NET 会将 enum 序列化为字符串或整数(取决于 StringEnumConverter 被应用)——但不是作为对象,因此没有机会对于 多态 "$type" 属性待补充.
解决的办法是,在序列化的时候,序列化一个可以传达具体类型信息的泛型包装类:
然后在序列化你的类时使用序列化包装器:
这会产生如下 JSON:
<块引用>
I have a fairly generic 'rule' class that I am using to drive the behavior of an analysis engine I'm writing:
RuleType is a specific enum, like so:
Using Json.NET, that both serializes and deserializes just fine.
RuleEnum, however, is giving me problems. Whether using the default enum serialization or the string enum serialization, the specific type of enum is not provided. As such, during deserialization, I am left with System.Enum
and a string value, which is wholly unhelpful.
This is an example of the serialization, to show what I'm talking about:
RuleFlagEnum, in this case, is referring to the enum:
I have tried using all of the TypeNameHandling
options inside Json.NET. They only put type hinting on the objects, which doesn't help with RuleFlagEnum since it is technically a primitive.
I would really, really like to keep the enum at System.Enum so we can load any arbitrary enum in for later interpretation by the rule type, so the entire thing is more expandable. Is this possible?
The difficulty here is that System.Enum
is an abstract class, so it is impossible to deserialize a value of unknown concrete type as such a type. Rather, one needs to have the specific type information in the JSON somewhere, however Json.NET will serialize an enum
as a string or an integer (depending upon whether a StringEnumConverter
is applied) -- but not an as an object, thus leaving no opportunity for a polymorphic "$type"
property to be added.
The solution is, when serializing, to serialize a generic wrapper class that can convey the concrete type information:
Then use serialize the wrapper when serializing your class:
This produces JSON like the following:
这篇关于将特定枚举反序列化为 Json.Net 中的 system.enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!