Petruza
Petruza

Reputation: 12276

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

I'm using JavaScriptSerializer.Deserialize() to get data from a JSON file.
But it ignores the decimal period, although using .GetType() on 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 the JSON:

{ "num": 3.14 }  

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

PS: I'm new to .NET as you can see.

Upvotes: 4

Views: 1488

Answers (2)

Sentinel
Sentinel

Reputation: 3697

I was having the same problem in a WCF service hosted in IIS/WAS, where I was using this class to deserialise some 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. 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.

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?) . Decimals will not deserialise correctly with an incompatible CurrentCulture.

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20638

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"]);

Upvotes: 1

Related Questions