Json.NET隐式转换 [英] Json.NET implicit casting

查看:84
本文介绍了Json.NET隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

class Sometype
{
    public Number pos { get; set; }
}

class Number
{
    private uint num;

    private Number(uint num)
    {
        this.num = num;
    }

    public static implicit operator uint(Number sid)
    {
        return sid.num;
    }

    public static implicit operator Number(uint id)
    {
        return new Number(id);
    }
}

这个json:{"pos":123}

当我尝试反序列化时,我得到了JsonException Error converting value 123 to type 'Tester2.Program+Number'..请告诉我.

When I try to deserialize this, I get a JsonException Error converting value 123 to type 'Tester2.Program+Number'.. Please advise me.

推荐答案

如果添加从longNumberimplicit(或explicit)转换,则可以正常工作.

If you add an implicit (or explicit) conversion from long to Number, this will work fine.

JSON.NET与long一起使用,因此永远不会调用您从uint进行的转换.例如:

JSON.NET works with longs when dealing with integral types, not uints, and so your cast from uint is never called. For example:

class Number
{
    private uint num;

    private Number(uint num)
    {
        this.num = num;
    }

    public static implicit operator Number(uint id)
    {
        return new Number(id);
    }

    public static implicit operator Number(long id)
    {
        return new Number((uint)id);
    }

    public static implicit operator uint(Number sid)
    {
        return sid.num;
    }
}

显然,这可能会导致溢出错误,因此请小心.另一个解决方案是创建一个自定义转换器来处理此问题(如果要序列化和反序列化此类型,可能值得研究).

Obviously this could result in overflow errors, so be careful. Another solution would be to create a custom converter to handle this (might be worth looking into if you're serializing and deserializing this type).

这是一个可行的示例: https://dotnetfiddle.net/MP4E3N

这篇关于Json.NET隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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