且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSON 序列化时如何本地化?

更新时间:2022-10-19 15:27:24

用于序列化十进制值的 JSON 标准不提供本地化格式.(请参阅 JSON.org.)这就是为什么值总是使用不变文化进行格式化的原因.

如果您需要本地化的值,那么您需要为您选择的序列化程序创建一个自定义转换器,该转换器将小数输出为预先格式化的字符串.在 Json.Net 中,这可以很容易地完成,如下所示:

class 程序{静态无效主(字符串 [] args){列表values = new List{ 1.1M, 3.14M, -0.9M, 1000.42M };var 转换器 = 新的 FormattedDecimalConverter(CultureInfo.GetCultureInfo("fr-FR"));string json = JsonConvert.SerializeObject(values, converter);Console.WriteLine(json);}}类 FormattedDecimalConverter : JsonConverter{私人文化信息文化;公共 FormattedDecimalConverter(CultureInfo 文化){this.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));}公共覆盖对象 ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){抛出新的 NotImplementedException();}}

输出:

["1,1","3,14","-0,9","1000,42"]

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.

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