开发者

How to localize when JSON-serializing?

开发者 https://www.devze.com 2023-02-05 09:52 出处:网络
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.

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 w开发者_如何学Goith this serializers, my guess is that there should be a proper way to do this.

Thanks in advance.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号