Json.NET implicit casting

怎甘沉沦 提交于 2019-12-11 01:58:22

问题


I have this code :

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);
    }
}

And this json : {"pos":123}

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


回答1:


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

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).

Here's a working example: https://dotnetfiddle.net/MP4E3N




回答2:


Full source for Console app/Any CPU is below. If this doesn't work for you change the declaration of pos to be of type object and then do pos.GetType() to see what you are actually getting if not an Int64.

using System;
using Newtonsoft.Json;


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(Int64 id)
    {
        return new Number((uint)id);
    }

}

class Program
{
    static void Main()
    {
        Sometype thing = JsonConvert.DeserializeObject<Sometype>("{\"pos\":123}");
    }
}


来源:https://stackoverflow.com/questions/34164920/json-net-implicit-casting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!