反序列化派生类时如何忽略基类JsonConverter? [英] How to ignore base class JsonConverter when deserializing derived classes?
问题描述
我有一个抽象基类:
[JsonConverter(typeof(Converter))]
public abstract class TextComponent {
...
public bool Bold { get; set; }
public TextComponent[] Extra { get; set; }
...
}
还有更多继承自它的类.这些类之一是StringComponent
:
And more classes which inherits from it. One of those classes is StringComponent
:
public sealed class StringComponent : TextComponent
{
public string Text { get; set; }
public StringComponent(string text)
{
Text = text;
}
}
Converter
,它是应用于TextComponent
的JsonConverter
,看起来像这样:
Converter
, which is a JsonConverter
applied to TextComponent
looks like this:
private sealed class Converter : JsonConverter
{
....
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var tok = JToken.Load(reader);
switch (tok)
{
...
case JObject x:
var dic = (IDictionary<string, JToken>) x;
if (dic.ContainsKey("text")) return x.ToObject<StringComponent>();
...
...
}
}
...
public override bool CanConvert(Type objectType) => objectType == typeof(TextComponent);
}
问题:
var str = "{\"text\":\"hello world\"}";
var obj = JsonConvert.DeserializeObject<TextComponent>(str);
// this doesn't work either:
var obj = JsonConvert.DeserializeObject<StringComponent>(str);
这进入一个无限的循环",最终导致一个StackOverflow
,因为在调用DeserializeObject<Stringcomponent>
或ToObject<StringComponent>
时,使用了基类的JsonConverter
(Converter
),它再次调用了这些方法.这不是所需的行为.序列化派生类时,它们不应使用基类的JsonConverter
.如果您查看Converter
的CanConvert
方法,我也只允许将它用于TextComponent
,而不允许其用于任何派生类.
This goes into an infinite "loop" eventually resulting in a StackOverflow
, because when calling DeserializeObject<Stringcomponent>
or ToObject<StringComponent>
, the JsonConverter
of the base class (the Converter
) is used which again calls those methods. This is not the desired behavior. When serializing derived classes, they should not be using base class's JsonConverter
. If you look at CanConvert
method of the Converter
, I'm also only allowing it for TextComponent
only, not for any of it's derived classes.
那我该如何解决呢?
推荐答案
您是否尝试从基类中删除[JsonConvert]属性?在我的示例中,我手动调用了自定义"转换器:
Did you try to remove the [JsonConvert]-attribute from your base class? In my example I invoke my "custom" converter manually: https://github.com/Code-Inside/Samples/blob/b635580a4966b1b77c93a8b682389c6cf06d2da6/2015/JsonConvertIssuesWithBaseClasses/JsonConvertIssuesWithBaseClasses/Program.cs#L36-L79
这篇关于反序列化派生类时如何忽略基类JsonConverter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!