Newtonsoft JSON应该序列化和继承 [英] Newtonsoft JSON ShouldSerialize and inheritance

查看:94
本文介绍了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;
    }
}

这篇关于Newtonsoft JSON应该序列化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆