Newtonsoft JSON应该序列化和继承
问题描述:
我有一个这样的班级:
public class Foo
{
public int Bar { get; set;}
}
该类用于存储在NoSQL数据库中,因此我需要存储 Bar
值.但是,我不想通过我的API公开此值.因此,我创建了一个继承自 Foo
的类,该类将从我的API返回.
This class is used to be stored in a NoSQL database so I need to store the Bar
value. However, I don't want to expose this value through my API.
So I created a class that inherits from Foo
that I will return from my API.
我按照发现的文档创建了 ShouldSerializeBar
方法
I created the method ShouldSerializeBar
by following the documentation I found here.
public class Foo2 : Foo
{
public bool ShouldSerializeBar()
{
return false;
}
}
但是,没有调用该方法.是否有解决此问题的方法或实现此目的的另一种方法?
However, the method is not called. Is there a workaround for this or another way to achieve this?
答
public class Foo
{
public int Bar { get; set;}
public virtual bool ShouldSerializeBar()
{
return true;
}
}
public class Foo2 : Foo
{
public override bool ShouldSerializeBar()
{
return false;
}
}