Home > Enterprise >  Flutter: json_serializable from json file path
Flutter: json_serializable from json file path

Time:11-25

import 'package:gameP/src/country_list.json'
    as countryList;

var a = CountryList.fromJson(countryList);

json file

[
  {
    "country": "AD",
    "lat": 42.546245,
    "long": 1.601554,
    "name": "Andorra"
  },
  {
    "country": "AE",
    "lat": 23.424076,
    "long": 53.847818,
    "name": "United Arab Emirates"
  }, 
  ....
]

json_serializable

@JsonSerializable()
class CountryList {
  final List<CountryListDetail> countryList;

  CountryList(this.countryList);

  factory CountryList.fromJson(Map<String, dynamic> json) =>
      _$CountryListFromJson(json);

  Map<String, dynamic> toJson() => _$CountryListToJson(this);
}

@JsonSerializable()
class CountryListDetail {
  final String? country;
  final String? name;
  final double? lat;
  final double? long;

  CountryListDetail(
      this.countryCode, this.countryName, this.lat, this.long);

  factory CountryListDetail.fromJson(Map<String, dynamic> json) =>
      _$CountryListDetailFromJson(json);

  Map<String, dynamic> toJson() => _$CountryListDetailToJson(this);
}

I am trying to convert this json file inside my directory using the json_serializable package.

The argument type 'CountryListModel' can't be assigned to the parameter type 'List<CountryListModel>?'.

The name 'countryList' refers to an import prefix, so it must be followed by '.'.
Try correcting the name to refer to something other than a prefix, or renaming the prefix.

However, I am getting these issues. How can I import this json file and convert into var = a using .fromJson();?

CodePudding user response:

Change one of countryList names for example :

import 'package:gameP/src/country_list.json' as countryListClass;
  • Related