【问题标题】:Is there a way to specify a type must fail deserialization unless a custom converter is used?除非使用自定义转换器,否则有没有办法指定类型必须反序列化失败?
【发布时间】:2018-06-18 12:35:00
【问题描述】:

假设我有一个类Foo,它有一个自定义转换器,

public class FooConverter : JsonConverter { ...

FooConverter 存在的原因是普通反序列化器创建的Foo 会导致初始化不正确的实例。所以FooConverter 必须始终用于序列化/反序列化Foo 的实例。

目前,我通过在 Foo 中有一个私有构造函数来实现这一点,它有一个参数:

class Foo
{
    private Foo(int _) {}

    public Foo(string x, string y) : this(0)
    {
        ...

现在任何让 Json.NET 与 Foo 一起工作的尝试都将导致 JsonSerializationException。除非FooConverter 被注册和使用。

但这看起来真的很乱。我假设必须有一种标记类的方法,例如使用属性来告诉 Json.NET 不要反序列化它? All I can find is the ConstructorHandling enum,但它没有“不使用非公共构造函数”选项。

我是否遗漏了什么,还是我必须继续使用我的“hack”方法?

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    所以FooConverter 必须始终用于序列化/反序列化Foo 的实例。

    然后注释类:

    [JsonConverter(typeof(FooConverter))]
    public class Foo
    {
    }
    

    【讨论】:

    • 完美。不知道我是怎么错过的,但这正是我所需要的!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2021-09-21
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多