using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Abp.Collections.Extensions; using Abp.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Abp.Localization.Dictionaries.Json { /// /// This class is used to build a localization dictionary from json. /// /// /// Use static Build methods to create instance of this class. /// public class JsonLocalizationDictionary : LocalizationDictionary { /// /// Private constructor. /// /// Culture of the dictionary private JsonLocalizationDictionary(CultureInfo cultureInfo) : base(cultureInfo) { } /// /// Builds an from given file. /// /// Path of the file public static JsonLocalizationDictionary BuildFromFile(string filePath) { try { return BuildFromJsonString(File.ReadAllText(filePath)); } catch (Exception ex) { throw new AbpException("Invalid localization file format! " + filePath, ex); } } /// /// Builds an from given json string. /// /// Json string public static JsonLocalizationDictionary BuildFromJsonString(string jsonString) { JsonLocalizationFile jsonFile; try { jsonFile = JsonConvert.DeserializeObject( jsonString, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } catch (JsonException ex) { throw new AbpException("Can not parse json string. " + ex.Message); } var cultureCode = jsonFile.Culture; if (string.IsNullOrEmpty(cultureCode)) { throw new AbpException("Culture is empty in language json file."); } var dictionary = new JsonLocalizationDictionary(CultureInfo.GetCultureInfo(cultureCode)); var dublicateNames = new List(); foreach (var item in jsonFile.Texts) { if (string.IsNullOrEmpty(item.Key)) { throw new AbpException("The key is empty in given json string."); } if (dictionary.Contains(item.Key)) { dublicateNames.Add(item.Key); } dictionary[item.Key] = item.Value.NormalizeLineEndings(); } if (dublicateNames.Count > 0) { throw new AbpException( "A dictionary can not contain same key twice. There are some duplicated names: " + dublicateNames.JoinAsString(", ")); } return dictionary; } } }