Home > Software design >  JsonSerializable to Json throws return error
JsonSerializable to Json throws return error

Time:05-09

I am trying to use this package - https://pub.dev/packages/json_serializable to help me with parsing data from api. However I am facing the error below and I am not sure how to fix it.

I get this error A value of type 'Location' can't be returned from the method 'toJson' because it has a return type of 'Map<String, dynamic>

@JsonSerializable()
class Location {
  const Location({
    required this.title,
    required this.locationType,
    required this.latLng,
    required this.woeid,
  });

  final String title;
  final LocationType locationType;
  final LatLng latLng;
  final int woeid;

  factory Location.fromJson(Map<String,dynamic> json) => _$LocationFromJson(json);
  Map<String, dynamic> toJson() => _$LocationFromJson(this);
}

Whenever I change the last part to Location toJson() => _$LocationFromJson(this); then I get error The argument type 'Location' can't be assigned to the parameter type 'Map<String, dynamic>

CodePudding user response:

You need to convert complex data type to simple ones such as String, int, double, etc. to parse in json. Here's an example on how to implement Latitude and Longitude.

Suppose I have a School Data for which I want to store name and Location. I would create a simple String for name but a separate class for Location. Here's how it would go:

class SchoolDataModel {
  final String name;
  final SchoolLocation schoolLocation;

  SchoolDataModel({
    required this.name,
    required this.schoolLocation,
  });

  factory SchoolDataModel.fromJson(Map<String, dynamic> parsedJson) =>
      SchoolDataModel(
        name: parsedJson['name'] as String,
        schoolLocation: SchoolLocation.fromJson(
            parsedJson['location'] as Map<String, dynamic>),
      );
}

As you can see SchoolLocation.fromJson is used to parse the location data using its own constructor. This is shown below:

class SchoolLocation {
  final String latitude;
  final String longitude;

  SchoolLocation({
    required this.latitude,
    required this.longitude,
  });

  factory SchoolLocation.fromJson(Map<String, dynamic> parsedJson) =>
      SchoolLocation(
        latitude: parsedJson['latitude'] as String,
        longitude: parsedJson['longitude'] as String,
      );
}
  • Related