wcfserializationdatacontractserializerwebinvoke

WebInvoke/DataContractJsonSerializer, '1,6276' cannot be parsed as 'double'


I am using WCF WebInvokeAttribute for declarative JSON requests (DataContractJsonSerializer), with DataContractAttribute/DataMemberAttribute based serialization.

I'm using a service that supports returning JSON containing data based on different cultures. By default, this service uses en-US culture settings, which means the decimals separator will be ".".

I have a class that has a System.Double property. If I request data using a culture that uses "," as decimal separator, I get a SerializationException while trying to deserialize the value for this property, when parsing the System.Double:

"There was an error deserializing the object of type XXX. The value '1,6276' cannot be parsed as the type 'double'."

This is certainly because an invariant culture is used while parsing the Double. I hoped that setting the correct culture on the current thread would fix this, but it didn't.

So the services will break for any cultures that is not using "." as decimal separator.

Will appreciate help.

Thanks!


Solution

  • According to the JSON Specification, a number should be formatted using a period. In other words, the problem is not on the Deserializer part, it is on the Serializer part.

    If you absolutely have to use a comma separator, then I would recommend setting up the contract using a string for the property type, and provide an additional property on your class that is not serialized to convert the string into a decimal (which you would then be able to pass whatever culture you needed to).