问题
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 long
s when dealing with integral types, not uint
s, 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