我有一个如下的类:
import 'package:json_annotation/json_annotation.dart';
part 'account_filter.g.dart';
@JsonSerializable()
class AccountFilter {
double latitude = 0;
double longitude = 0;
String city = "";
String country = "";
int minAge = 18;
int maxAge = 99;
int gender = 1;
AccountFilter(
this.latitude,
this.longitude,
this.city,
this.country,
this.minAge,
this.maxAge,
this.gender,
);
factory AccountFilter.fromJson(Map<String, dynamic> json) => _$AccountFilterFromJson(json);
Map<String, dynamic> toJson() => _$AccountFilterToJson(this);
}
dart run build_runner build --delete-conflicting-outputs
生成的文件看起来像这样:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'account_filter.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AccountFilter _$AccountFilterFromJson(Map<String, dynamic> json) =>
AccountFilter(
(json['latitude'] as num).toDouble(), // <-- IMPORTANT!!!
(json['longitude'] as num).toDouble(), // <-- IMPORTANT!!!
json['city'] as String,
json['country'] as String,
json['minAge'] as int,
json['maxAge'] as int,
json['gender'] as int,
);
Map<String, dynamic> _$AccountFilterToJson(AccountFilter instance) =>
<String, dynamic>{
//... some code
};
在反序列化期间,我收到以下错误type 'String' is not a subtype of type 'num' in type cast
当然,问题出在线路上
json['latitude'] as num).toDouble(),
我怎样才能优雅地解决这个问题?在我最初的解决方案中,我将longitude
和latitude
设置为字符串,将它们重命名为longitudeString
和latitudeString
,并创建了两个getter:
double get latitude => double.parse(latitudeString);
double get longitude => double.parse(longitudeString);
但我正在寻找更方便的解决方案。
1条答案
按热度按时间wkyowqbh1#
我是这样解决的。
首先,我定义了public方法:
我对
AccountFilter
类做了以下更改:基本上,我将方法
toDouble
设置为@JsonKey
注解中的fromJson
参数,用于正确解析数据。