How to serialize GeoPoint using dart json_serializable package

Viewed 1476

I am trying to filter my Firestore collections by distance using the following package.

https://github.com/fluttercommunity/firestore_helpers

Referring to their example they are using jaguar_serializer to convert the data received from Firestore to Location class. I have implement their getDataInArea function in my app but I am currently stuck because I am using json_serializable.

I have looked around and found that there is a suggestion on how to handle GeoPoint if using built_value at the following link.

https://github.com/google/built_value.dart/issues/417#issuecomment-391661750

So I am wondering is there a way to implement something like what is shown in jaguar_serializer and built_value but using json_serializable package instead.

I am guessing that one way is to use @JsonKey(fromJson: , toJson: ) but I am not too sure about how to get about doing it.

3 Answers

After a bit more digging and trying to understand how things works. I have managed to solve my problem by writing the following in my class.

  @JsonKey(fromJson: _fromJsonGeoPoint, toJson: _toJsonGeoPoint)
  GeoPoint location;

  static GeoPoint _fromJsonGeoPoint(GeoPoint geoPoint) {
    return geoPoint;
  }

  static GeoPoint _toJsonGeoPoint(GeoPoint geoPoint) {
    return geoPoint;
  }

I guess the idea is just to not make any changes to the GeoPoint object. Anyway would love to hear it this is the right way or there is a better way of doing this. Cheers!

Your solution didn't work for me. If you try for instance a jsonEncode on your object, it will fail. Other people feedback is welcomed. This is what I suggest:

@JsonKey(fromJson: _fromJsonGeoPoint, toJson: _toJsonGeoPoint)
GeoPoint position;

static GeoPoint _fromJsonGeoPoint(GeoPoint geoPoint) { return geoPoint; }

///A Map should be returned here to properly generate the json
static Map<String, dynamic> _toJsonGeoPoint(GeoPoint geoPoint) {
return {"latitude": geoPoint.latitude, "longitude":
geoPoint.longitude};
}

The type returned from Firestore is a GeoPoint, you can just pass it through using JsonConverter:

class GeoPointConverter
    implements JsonConverter<GeoPoint, GeoPoint> {
  const GeoPointConverter();

  @override
  GeoPoint fromJson(GeoPoint geoPoint) {
    return geoPoint;
  }

  @override
  GeoPoint toJson(GeoPoint geoPoint) =>
      geoPoint;
}

After that, annotate your parameter: @GeoPointConverter() required GeoPoint location

Related