简体   繁体   English

Json.Net::Deserialize + Unboxing from object

[英]Json.Net::Deserialize + Unboxing from object

class MyObj
{
    private int _Max;
    public object Max
    {
        get
        {
            return (int)_Max;
        }
        set
        {
            _Max = (int)value;
        }
    }
}

Program.cs程序.cs

MyObj obj1 = new MyObj(100);
string json = JsonConvert.SerializeObject(obj1, Formatting.Indented);
obj1.Max = 200;
MyObj obj2 = JsonConvert.DeserializeObject<MyObj>(obj1);

When ran, it crashed on the last line of Program.CS (Deserialize) while doing a Set on the Max property运行时,它在对 Max 属性执行 Set 时在 Program.CS (Deserialize) 的最后一行崩溃

An exception of type 'System.InvalidCastException' occurred in Supremacy.exe but was not handled in user code Supremacy.exe 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理

Why does my Set to 200, works but the Deserialize does not?为什么我的设置为 200 有效但反序列化无效? I debugged and the 200 value that is tried to be Set into obj2 is an object containing an int.我调试并尝试设置为 obj2 的 200 值是一个包含 int 的 object。

If there is no setter on max, Program.cs run properly如果 max 上没有设置器,Program.cs 可以正常运行

Explain me why and how to fix it:)解释我为什么以及如何解决它:)

PS: I'm using box/unboxing because MyObj is part of a hierarchy and it could be any primitive type that would be used as a Max. PS:我正在使用装箱/拆箱,因为 MyObj 是层次结构的一部分,它可以是任何可用作 Max 的原始类型。

To solve the issue of exception use Convert.ToInt32 : 要解决异常问题,请使用Convert.ToInt32

public object Max
{
    get
    {
        return (int)_Max;
    }
    set
    {
        _Max = Convert.ToInt32(value);
    }
}

I think the issue happens because after deserializing the value compiler doesn't know if it's originally been an integer. 我认为发生此问题是因为在对值编译器进行反序列化之后,它不知道它最初是否是整数。 All it has is this string: 它所具有的只是这个字符串:

{
  "Max": 100
}

So the value of 100 is consumed as a string. 因此,将100的值作为字符串使用。 And .Net has a prevention mechanism that does not allow boxing one type (eg decimal) and unboxing to a different type (eg integer). .Net具有一种预防机制,该机制不允许将一种类型(例如十进制)装箱和将另一种类型(例如整数)装箱。 Here the cast happens from string to integer so it's not allowed as well. 这里的转换是从字符串到整数的,所以也不允许。 More details on that in this answer . 有关此答案的更多详细信息。

Flagging a line...标记一行...

return (int)_Max;

Line 5 should be第 5 行应该是

return (object)_Max;

because on line 1, Max is object.因为在第 1 行,Max 是 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM