arrays - Flutter 解析来自本地化 JSON 文件的数组

标签 arrays json flutter dart

我正在尝试将城市名称数组添加到我的本地化 json 文件中,但在将其转换为字符串后我无法将其解码回数组。
en-US.json

{
  "title" : "My account",
  "name" : "John",
  "cities" : ["Paris", "Lyon", "Nice"]
}
AppLocalization.dart
class AppLocalizations {
  final Locale locale;

  AppLocalizations(this.locale);

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  static const LocalizationsDelegate<AppLocalizations> delegate =
      _AppLocalizationsDelegate();

  Map<String, String> _localizationStrings;

  Future<bool> load() async {
    String jsonString = await rootBundle.loadString(
        'assets/translations/${locale.languageCode}-${locale.countryCode}.json');

    Map<String, dynamic> jsonMap = json.decode(jsonString);

    _localizationStrings = jsonMap.map((key, value) {
      return MapEntry(key, value.toString());
    });
    return true;
  }

  Future<void> setLocale(Locale locale) async {
    final SharedPreferences _prefs = await SharedPreferences.getInstance();
    final _languageCode = locale.languageCode;
    await _prefs.setString('locale', _languageCode);
    print('locale saved!');
  }

  static Future<Locale> getLocale() async {
    final SharedPreferences _prefs = await SharedPreferences.getInstance();
    final String _languageCode = _prefs.getString('locale');
    if (_languageCode == null) return null;

    Locale _locale;
    _languageCode == 'en'
        ? _locale = Locale('en', 'US')
        : _locale = Locale('ar', 'EG');
    return _locale;
  }

  String translate(String key) {
    return _localizationStrings[key];
  }
}

class _AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'ar'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localization = AppLocalizations(locale);
    await localization.load();
    return localization;
  }

  @override
  bool shouldReload(LocalizationsDelegate<AppLocalizations> old) {
    return false;
  }
}
在我的小部件中,我尝试通过 List<String> _cities = AppLocalization.of(context).translate('cities'); 访问数组
这有效,如果我打印 _cities.toString() 它会打印 [Paris, Lyon, Nice]。
问题
当我尝试使用 json.decode(_cities) 将 _cities 解码为数组时我总是收到格式错误 Unhandled Exception: FormatException: Unexpected character (at character 2)。
我相信在这个函数中数组被转换为字符串
_localizationStrings = jsonMap.map((key, value) {
  return MapEntry(key, value.toString());
});
如何将其解析回数组?
我愿意接受各种建议。谢谢

最佳答案

我知道这可能不是最好的方法,但这只是我发现的一种方法。您还可以将您的值保存在不同的 json Assets 文件中,并使用 json.decode() 正常解析它,但我需要它来通过本地化更轻松地处理它。
所以我找到了一个简单的解决方案,而不是向本地化类添加函数。
我从我的本地化文件(像任何其他本地化字符串)中以字符串的形式获取小部件中的数组,如下所示:

var list = AppLocalization.of(context).translate('cities');//this will return [Paris, Lyon, Nice] as a string
然后我执行以下操作:
list = list.replaceAll(RegExp("\\[|\\]"), ''); //removes square brackets from the string
var cityList = list.split(','); //splits the city names by the comma as a 
print(cityList); //prints [Paris, Lyon, Nice] as List<String>
我还实现了另一种获取嵌套 json 数组的方法,例如
{
  "title" : "My account",
  "name" : "John",
  "cities" : ["Paris", "Lyon", "Nice"],
  "areas" : 
  {
     "paris" : ["area1", "area2", "area3"], 
     "lyon": ["area1", "area2", "area3"]
  }
}
我这样做是为了获得巴黎地区...
  var areas = AppLocalization.of(context).translate('areas'); //this gets the whole map as a string.
  areas = areas.replaceAll(RegExp("\\[|\\]|\\{|\\}"), '');//this removes leading and trailing {[ ]}
  var splitValues = areas.split(':');
  var mapValues = Map.fromIterable(test, key: (item) => splitValues[0],value: (item) => item.split(','),);

    var parisAreas = mapValues.map((key, value) =>
    MapEntry<String, List<String>>(key, List<String>.from(value)));

关于arrays - Flutter 解析来自本地化 JSON 文件的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64202118/

相关文章:

字符数组

c - 声明一个 long long 数组,大小为 unsigned int

javascript - JavaScript 中的 xml 到 json

flutter - 如何在 Flutter 中 stub 目标平台

android - Flutter Android Studio 中缺少设备文件资源管理器选项

arrays - 无法转换数组中的返回表达式

java - Java 字符数组是否始终是有效的 UTF-16(Big Endian)编码?

javascript - 将 JSON 扁平化为没有 ID 的层次结构/树

javascript - 使用 angularjs 和 JSON 从数据库获取数据

button - 我们如何在 flutter 中按下的单个按钮中执行两个功能