Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to localize when JSON-serializing?

I've been struggling for a few hours now with no good result. I'm trying to use .NET JSON Serializers for converting JSON back and forth from the UI into objects.

The problem arises with decimals because the standard for my culture has "," as decimal separator instead of ".". I've tried implementing a custom converter (see this question) with no good results.

I've also checked out NewtonSoft JSON.net without better results. So far it seems that matching with value types is done culture-invariantly. I want to override this behavior, how to do it?

BTW, I really wish to avoid localizing on the javascript side. I definitely want .NET to take care of cross-culture formatting and localizing, I don't think there should be exceptions like I'm finding with this serializers, my guess is that there should be a proper way to do this.

Thanks in advance.

like image 657
Alpha Avatar asked Jan 18 '11 06:01

Alpha


People also ask

What is serializing in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is JSON serialization exception?

JsonSerializationException(String, String, Int32, Int32, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.

Does JSON serialize data?

JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.

Why do we need to serialize JSON?

The purpose of serializing it into JSON is so that the message will be a format that can be understood and from there, deserialize it into an object type that makes sense for the consumer.


2 Answers

The JSON standard for serializing decimal values does not provide for localized formatting. (See JSON.org.) This is why values are always formatted with the Invariant culture.

If you need localized values, then you'll need to create a custom converter for your serializer of choice which outputs the decimals as pre-formatted strings instead. In Json.Net, this can be done easily as shown below:

class Program
{
    static void Main(string[] args)
    {
        List<decimal> values = new List<decimal> { 1.1M, 3.14M, -0.9M, 1000.42M };

        var converter = new FormattedDecimalConverter(CultureInfo.GetCultureInfo("fr-FR"));
        string json = JsonConvert.SerializeObject(values, converter);

        Console.WriteLine(json);
    }
}

class FormattedDecimalConverter : JsonConverter
{
    private CultureInfo culture;

    public FormattedDecimalConverter(CultureInfo culture)
    {
        this.culture = culture;
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(decimal) ||
                objectType == typeof(double) ||
                objectType == typeof(float));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(Convert.ToString(value, culture));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Output:

["1,1","3,14","-0,9","1000,42"]
like image 60
Brian Rogers Avatar answered Sep 21 '22 08:09

Brian Rogers


Are you setting proper CultureInfo on your current thread's CurrentCulture and CurrentUICulture properties?

like image 24
Jakub Konecki Avatar answered Sep 19 '22 08:09

Jakub Konecki