Reputation: 496
Is there a way to serialize a JsonResult in a controller considering the current locale? In my case when the language is set to italian I wish separator for decimal values was ',' instead of '.'.
JsonDataTable<SomeObj> res = new JsonDataTable<SomeObj>(someObjList);
return new JsonResult(res);
Upvotes: 2
Views: 3327
Reputation: 1664
Here’s an example of culture-specific decimal converter - copied from here:
using System.Text.Json;
using System.Text.Json.Serialization;
public class CultureSpecificQuotedDecimalConverter : JsonConverter<decimal>
{
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
return Convert.ToDecimal(reader.GetString(), System.Globalization.CultureInfo.GetCultureInfo("es-ES"));
}
else
{
return reader.GetInt32();
}
}
//Write() not shown
}
Use like this:
using System.Text.Json;
var jsonOptions = new JsonSerializerOptions();
jsonOptions.Converters.Add(new CultureSpecificQuotedDecimalConverter());
var movie = JsonSerializer.Deserialize<Movie>(movieJson, jsonOptions);
Console.WriteLine($"Year={movie.YearReleased} Revenue={movie.Revenue}");
Upvotes: 1