Category / Section
How to perform localization using JSON in a Syncfusion Blazor app?
5 mins read
1. Follow this documentation for preparing localization sample and ignore the inclusion of .resx files.
2. Create a JSON file named wwwroot/Resources.json and populate it with key-value pairs for each localized string.
Resources.json
{
"Grid_GroupDropArea": {
"en-US": "Drag a column header here to group its column",
"ar-AE": "اسحب رأس العمود هنا لتجميع العمود",
"it-IT": "Trascina qui un'intestazione di colonna per raggruppare la sua colonna"
},
"Grid_Equal": {
"en-US": "Equal",
"ar-AE": "مساو",
"it-IT": "Uguale"
},
"Grid_EnterValue": {
"en-US": "Enter the value",
"ar-AE": "أدخل القيمة",
"it-IT": "Inserisci il valore"
},
//...
}
3. Create a class named Components/Layout/LocalizationService.cs, which is responsible for reading the JSON file containing localization resources and populating a dictionary with the extracted data. Please find the code snippet for reference:
LocalizationService.cs
using System.Text.Json;
namespace Sample.Shared
{
public class LocalizationService
{
private readonly Dictionary<string, Dictionary<string, string>> _resources;
public LocalizationService()
{
var filePath = "path/to/Resources.json"; // Replace "path/to/" with actual path to your file
var json = File.ReadAllText(filePath);
var document = JsonDocument.Parse(json);
_resources = new Dictionary<string, Dictionary<string, string>>();
foreach (var property in document.RootElement.EnumerateObject())
{
var translations = new Dictionary<string, string>();
foreach (var translation in property.Value.EnumerateObject())
{
translations.Add(translation.Name, translation.Value.GetString());
}
_resources.Add(property.Name, translations);
}
}
public string GetString(string key, string culture)
{
if(_resources.TryGetValue(key, out var translations))
{
if(translations.TryGetValue(culture, out var translation))
{
return translation;
}
}
return key;
}
}
}
4. Finally, in the Components/Layout/SyncfusionLocalizer.cs file, instantiate the LocalizationService and call the GetString(string key, string culture) method from the LocalizationService's object inside the GetText(string key) method. This method dynamically provides culture-specific resources at runtime. Please find the code snippet for reference:
SyncfusionLocalizer.cs
using Microsoft.AspNetCore.Components; using Syncfusion.Blazor;
using System.Globalization;
using System.Resources; namespace Sample.Shared
{
public class SyncfusionLocalizer : ISyncfusionStringLocalizer
{
LocalizationService Localization = new LocalizationService();
public ResourceManager ResourceManager => throw new NotImplementedException();
public string GetText(string key)
{
CultureInfo currentCulture = CutureInfo.CurrentCulture;
return Localization.GetString(key, currentCulture.Name);
}
} }
5. Finally, you can run the Syncfusion Blazor app with JSON-based localization.