简体   繁体   English

.NET的JavaScriptSerializer.Deserialize()忽略来自JSON的数字的小数周期

[英].NET's JavaScriptSerializer.Deserialize() ignores decimal period in numbers from JSON

I'm using JavaScriptSerializer.Deserialize() to get data from a JSON file. 我正在使用JavaScriptSerializer.Deserialize()从JSON文件中获取数据。
But it ignores the decimal period, although using .GetType() on the value, returns System.Decimal . 但它忽略了小数时段,尽管在值上使用.GetType() ,返回System.Decimal

This is the C# code: 这是C#代码:

JavaScriptSerializer jss = new JavaScriptSerializer();          
Dictionary< string, object > dic = jss.Deserialize< Dictionary< string, object >>( json );

This is the JSON: 这是JSON:

{ "num": 3.14 }  

I try this: Console.WriteLine ( "{0} {1}", dic["num"].GetType(), dic["num"] ); 我试试这个: Console.WriteLine ( "{0} {1}", dic["num"].GetType(), dic["num"] );
And get this: System.Decimal 314 得到这个: System.Decimal 314

PS: I'm new to .NET as you can see. PS:你可以看到我是.NET的新手。

You must be doing something else you are not telling us. 你必须做一些你没有告诉我们的事情。

Here is complete working code: 这是完整的工作代码:

String json = " { \"num\": 3.14 }";
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> dic = jss.Deserialize<Dictionary<string, object>>(json);

String test = String.Format("{0} {1}", dic["num"].GetType(), dic["num"]);

I was having the same problem in a WCF service hosted in IIS/WAS, where I was using this class to deserialise some JSON. 我在IIS / WAS中托管的WCF服务中遇到了同样的问题,我正在使用此类来反序列化一些JSON。 The problem appeared after the service was moved from one production server to another, where the culture settings were different. 服务从一个生产服务器移动到另一个生产服务器之后出现问题,其中文化设置不同。

The root problem turned out to be different. 根本问题结果是不同的。 Even though the App Pool under which the WCF service was running was for an identity with the correct culture, immediately after a server reboot the process under which this service was running turned out to have either the wrong identity or wrong culture. 尽管运行WCF服务的应用程序池是用于具有正确文化的标识,但是在服务器重新启动之后,立即运行此服务的过程被证明具有错误的标识或错误的文化。 We still haven't figured out where the problem is exactly, but it is either due to ThreadPool contamination (threads returned to thread pool do not reset their culture), or a bug in AppFabric autostart... perhaps. 我们仍然没有弄清楚问题究竟在哪里,但这可能是由于ThreadPool污染(返回到线程池的线程没有重置其文化),或者是AppFabric自动启动中的错误......也许。

In any case, the problem in the original post is down to wrong CurrentCulture, and perhaps an incorrect implementation of the JavaScriptSerializer (is it not the case that JSON norms mandate a decimal dot for decimals?) . 在任何情况下,原始帖子中的问题都归结为错误的CurrentCulture,也许是JavaScriptSerializer的错误实现(JSON规范是否要求小数点小数点?)。 Decimals will not deserialise correctly with an incompatible CurrentCulture. 使用不兼容的CurrentCulture时,小数不会正确反序列化。

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

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