6
  • I'm working with geocoder library in flutter.
  • When I get an Address I want to save it in firebase
    firestore
    as an user (object) atribute but to do that I need to
    serialize the address (convert it to a map).
  • Currently, I'm using json_serializable to parse from/to map my User class.
  • Because Address is a class from geocoder library I'm having troubles to parse it to/from map because this is handled by json_serializable.

This is my User class:

    import 'package:geocoder/model.dart';
    import 'package:json_annotation/json_annotation.dart';

    import './resource.dart';

    part 'user.g.dart';

    @JsonSerializable()
    class User extends Resource {
       User(this.email, this.name);

       String email;
       String name;
       List<Address> addresses;

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

       Map<String, dynamic> toJson() => _$UserToJson(this);
    }
  • I tried creating a new class called UserAddress whose parent would be Address like following but I'm getting an error

The constructor returns type 'Address' that isn't of expected type 'UserAddress'.dart(invalid_cast_new_expr)

in the named constructor UserAddress.fromJson:

import 'package:geocoder/geocoder.dart';
import 'package:json_annotation/json_annotation.dart';

part 'user-address.g.dart';

@JsonSerializable()
class UserAddress extends Address {
  UserAddress();

  factory UserAddress.fromJson(Map<String, dynamic> json) =>
      Address.fromMap(json);

  Map<String, dynamic> toJson() => this.toMap();
}

Please give me some options to achieve parsing to/from map, please.

1 Answer 1

12

If I got you right, you want to decorate library's class with your own. You can use @JsonKey annotation to set functions for (en)decoding library's Address object.

import 'dart:convert';

import 'package:geocoder/geocoder.dart';
import 'package:json_annotation/json_annotation.dart';

part 'user_address.g.dart';

@JsonSerializable()
class UserAddress {
  UserAddress(this.address, this.oneMoreField);

  @JsonKey(fromJson: _addressFromJson, toJson: _addressToJson)
  final Address address;
  final int oneMoreField;

  factory UserAddress.fromJson(Map<String, dynamic> json) => _$UserAddressFromJson(json);
  Map<String, dynamic> toJson() => _$UserAddressToJson(this);
}

String _addressToJson(Address address) => jsonEncode(address.toMap());
Address _addressFromJson(String json) => Address.fromMap(jsonDecode(json));

Example usage:

final testUserAddress = UserAddress(Address(
  addressLine: 'test',
  coordinates: Coordinates(10, 20)
), 1);

final json = testUserAddress.toJson();
print(json);

final decoded = UserAddress.fromJson(json);

prints:

{address: {"coordinates":{"latitude":10.0,"longitude":20.0},"addressLine":"test","countryName":null,"countryCode":null,"featureName":null,"postalCode":null,"locality":null,"subLocality":null,"adminArea":null,"subAdminArea":null,"thoroughfare":null,"subThoroughfare":null}, oneMoreField: 1}

As you can see, all nested objects are encoded fine.

UPD: When doing that via inheritence, you'll have to pass all base class' fields to super constructor and to override nested objects fields with @JsonKey annotation:

@JsonSerializable()
class UserAddress extends Address {
  UserAddress({String addressLine, String countryName, this.coordinates, this.oneMoreField}) 
    : super(addressLine: addressLine, countryName: countryName);

  @override
  @JsonKey(fromJson: _coordinatesFromJson, toJson: _coordinatesToJson)
  final Coordinates coordinates;

  final int oneMoreField;

  factory UserAddress.fromJson(Map<String, dynamic> json) => _$UserAddressFromJson(json);
  Map<String, dynamic> toJson() => _$UserAddressToJson(this);
}

String _coordinatesToJson(Coordinates coordinates) => jsonEncode(coordinates.toMap());
Coordinates _coordinatesFromJson(String json) => Coordinates.fromMap(jsonDecode(json));

result:

{addressLine: test, countryName: null, coordinates: {"latitude":10.0,"longitude":20.0}, oneMoreField: 1}

But I recommend using composition over inheritence in this case.

1
  • Can the answer be implemented removing the attribute Address in UserAddress because UserAddress extends Address in order to implement a solution to parsing UserAddress as Address directly? Nov 24, 2019 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.