.NET JavaScriptSerializer.Deserialize () ignores decimal period in numbers from JSON

I am using JavaScriptSerializer.Deserialize() to retrieve data from a JSON file.
But it ignores the decimal period, but using .GetType() for the value, returns System.Decimal .

This is the C # code:

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

This is JSON:

 { "num": 3.14 } 

I try this: Console.WriteLine ( "{0} {1}", dic["num"].GetType(), dic["num"] );
And get the following: System.Decimal 314

PS: I am new to .NET, as you can see.

+4
source share
2 answers

You must do something else that you are not telling us.

Here is the full 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"]); 
+1
source

I had the same problem in a WCF service hosted in IIS / WAS where I used this class to deserialize some JSON. The problem arose after the service was transferred from one production server to another, where the culture settings were different.

The root problem turned out to be different. Despite the fact that in the application pool in which the WCF service is running, for identification with the correct culture, immediately after the server reboot, the process in which the service is running was either incorrect or incorrect. We still have not figured out where the problem is exactly, but this is either due to ThreadPool pollution (threads returned to the thread pool, do not reset their culture), or an error in the AppFabric startup ... maybe.

In any case, the problem in the original post boils down to the incorrect CurrentCulture and, possibly, to the incorrect JavaScriptSerializer implementation (isn't it that the JSON standards define the decimal point for decimal places?). Decimals will not deserialize correctly with incompatible CurrentCulture.

0
source

Source: https://habr.com/ru/post/1447774/


All Articles