Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:json_annotation/json_annotation.dart';
- part 'location.g.dart';
- // * This logic was a bit complex, so I moved it out into a handy re-usable
- // * function, you could also make it not private, or add it to a utility class
- // * or something as a static method if you want to use it outside this file.
- double _parseDoubleOrDefault(String d, {double orElse = 0.0}) =>
- double.tryParse(d) ?? orElse;
- // * No Need to add a @JsonValue annotation to each member, the renaming method
- // * you wanted is handled by the JsonEnum annotation.
- @JsonEnum(fieldRename: FieldRename.pascal)
- enum LocationType {
- city,
- region,
- state,
- province,
- country,
- continent,
- }
- // * Your original sample was missing a toJson method on this model, I also
- // * removed the Converter annotation from LatLng.
- @JsonSerializable()
- class Location {
- const Location({
- required this.title,
- required this.locationType,
- required this.latLng,
- required this.woeid,
- });
- final String title;
- final LocationType locationType;
- @JsonKey(name: 'latt_long')
- final LatLng latLng;
- final int woeid;
- factory Location.fromJson(Map<String, dynamic> json) =>
- _$LocationFromJson(json);
- Map<String, dynamic> toJson() => _$LocationToJson(this);
- }
- class LatLng {
- const LatLng({
- required this.latitude,
- required this.longitude,
- });
- final double latitude;
- final double longitude;
- // * Removed the converter and moved these onto the model they were for.
- // * Dart's serializer api only cares if a model has a constructor named
- // * fromJson that takes 1 param, and a toJson method that returns the same
- // * type that fromJson takes.
- factory LatLng.fromJson(String jsonString) {
- final parts = jsonString.split(',').map(_parseDoubleOrDefault);
- return LatLng(
- latitude: parts.first,
- longitude: parts.last,
- );
- }
- String toJson() => '$latitude,$longitude';
- }
Advertisement
Add Comment
Please, Sign In to add comment