Guest User

Untitled

a guest
Feb 24th, 2022
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.95 KB | None | 0 0
  1. import 'package:json_annotation/json_annotation.dart';
  2.  
  3. part 'location.g.dart';
  4.  
  5. // * This logic was a bit complex, so I moved it out into a handy re-usable
  6. // * function, you could also make it not private, or add it to a utility class
  7. // * or something as a static method if you want to use it outside this file.
  8.  
  9. double _parseDoubleOrDefault(String d, {double orElse = 0.0}) =>
  10.     double.tryParse(d) ?? orElse;
  11.  
  12. // * No Need to add a @JsonValue annotation to each member, the renaming method
  13. // * you wanted is handled by the JsonEnum annotation.
  14.  
  15. @JsonEnum(fieldRename: FieldRename.pascal)
  16. enum LocationType {
  17.   city,
  18.   region,
  19.   state,
  20.   province,
  21.   country,
  22.   continent,
  23. }
  24.  
  25. // * Your original sample was missing a toJson method on this model, I also
  26. // * removed the Converter annotation from LatLng.
  27.  
  28. @JsonSerializable()
  29. class Location {
  30.   const Location({
  31.     required this.title,
  32.     required this.locationType,
  33.     required this.latLng,
  34.     required this.woeid,
  35.   });
  36.  
  37.   final String title;
  38.   final LocationType locationType;
  39.   @JsonKey(name: 'latt_long')
  40.   final LatLng latLng;
  41.   final int woeid;
  42.  
  43.   factory Location.fromJson(Map<String, dynamic> json) =>
  44.       _$LocationFromJson(json);
  45.  
  46.   Map<String, dynamic> toJson() => _$LocationToJson(this);
  47. }
  48.  
  49. class LatLng {
  50.   const LatLng({
  51.     required this.latitude,
  52.     required this.longitude,
  53.   });
  54.  
  55.   final double latitude;
  56.   final double longitude;
  57.  
  58.   // * Removed the converter and moved these onto the model they were for.
  59.   // * Dart's serializer api only cares if a model has a constructor named
  60.   // * fromJson that takes 1 param, and a toJson method that returns the same
  61.   // * type that fromJson takes.
  62.  
  63.   factory LatLng.fromJson(String jsonString) {
  64.     final parts = jsonString.split(',').map(_parseDoubleOrDefault);
  65.     return LatLng(
  66.       latitude: parts.first,
  67.       longitude: parts.last,
  68.     );
  69.   }
  70.  
  71.   String toJson() => '$latitude,$longitude';
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment