json 如何序列化GeoPointFlutter?

uqdfh47h  于 12个月前  发布在  Flutter
关注(0)|答案(2)|浏览(178)

flutter pub run build_runner build在geoPoint上给出了一个错误。错误说:要支持GeoPoint类型,你可以:使用JsonConverter。我如何实现它?

class

...
@JsonSerializable()
class Person{
  late final String name;
  final List<Location> location;

  Person(
      {required this.uid,
      required this.name,
      required this.location});

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json); 
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

@JsonSerializable()
class Location {
  String name;
  GeoPoint geoPoint;

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

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

字符串

7xzttuei

7xzttuei1#

颜色示例:

@JsonSerializable()
class Line {
  Line({required this.name, required this.color});

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

  String name;

  @ColorSerializer()
  Color color;
  

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

class ColorSerializer implements JsonConverter<Color, int> {
  const ColorSerializer();

  @override
  Color fromJson(int json) => Color(json);

  @override
  int toJson(Color color) => color.value;
}

字符串
你的代码应该是这样的:

@JsonSerializable()
class Line {
  Line({required this.name, required this.color});

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

  String name;

  @GeoPointSerializer()
  GeoPoint geoPoint;
  

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

class GeoPointSerializer implements JsonConverter<GeoJson, List<int,int>> {
  const GeoPointSerializer();

  @override
  GeoPoint fromJson(List<int,int> json) => GeoPoint(x:json[0],json[1]);

  @override
  List<int,int> toJson(GeoPoint geoPoint) => [geoPoint.x,geoPoint.y];
}

gijlo24d

gijlo24d2#

我也有同样的问题,
你可以这样使用;

class GeoPointJsonConverter extends JsonConverter<GeoPoint, List<double>> {
  const GeoPointJsonConverter();
  @override
  GeoPoint fromJson(List<double> json) {
    return GeoPoint(json[0], json[1]);
  }

  @override
  List<double> toJson(GeoPoint object) {
    return [object.latitude, object.longitude];
  }
}

字符串

相关问题