简体   繁体   English

使用牛顿JSON从C#中的反序列化JSON投射错误

[英]Casting error from deserialized json in c# using newton json

Unable to cast to int from deserialized json (dictionary object) 无法从反序列化的json(字典对象)转换为int

Here is the code: 这是代码:

Lets say you have dictionary object. 假设您有字典对象。

 Dictionary<string, object> dict = new Dictionary<string, object>();
 dict.Add("key", 1);

Now i serialize & deserialize it. 现在,我将其序列化和反序列化。

var serializedData = JsonConvert.SerializeObject(dict);
var deserializedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedData);

And getting error when i do this at runtime 当我在运行时这样做时出现错误

int value = (int)deserializedData["key"];

我相信错误是JSON.NET假设您提到的数字是long(int64)类型而不是整数(int32),因此当您对对象进行装箱时,您无法直接将其装箱到int32,因此您需要进行更改您的代码

 int i = (int)(long) deserializedData["key"];

Your number is being serialized as a long (Int64). 您的号码正在序列化为长整数(Int64)。 Try this: 尝试这个:

int value = (int)(long)deserializedData["key"];

You have to unbox the long first and then convert it to an int after it has been unboxed. 您必须先将长整型拆箱,然后再将其转换为整数。 This makes more sense if you convert the above to separate statements: 如果将以上内容转换为单独的语句,则更有意义:

object oValue = deserializedData["key"];
long longValue = (long)oValue;
int value = (int)longValue;

Because the type of deserializedData["key"] is Int64 (you'll see when you debug). 因为deserializedData["key"]的类型是Int64 (调试时会看到)。 You can't cast Int64 to int ( Int32 ) . 您不能将Int64intInt32 )。

what you can do: 你可以做什么:

int value = System.Convert.ToInt32(deserializedData["key"]);

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

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