json_serializable包在flutter中有问题地转换为double

kqlmhetl  于 2023-05-30  发布在  Flutter
关注(0)|答案(1)|浏览(178)

我有一个如下的类:

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(),

我怎样才能优雅地解决这个问题?在我最初的解决方案中,我将longitudelatitude设置为字符串,将它们重命名为longitudeStringlatitudeString,并创建了两个getter:

double get latitude => double.parse(latitudeString);
  double get longitude => double.parse(longitudeString);

但我正在寻找更方便的解决方案。

wkyowqbh

wkyowqbh1#

我是这样解决的。
首先,我定义了public方法:

double toDouble(String number) {
  return double.parse(number);
}

我对AccountFilter类做了以下更改:

@JsonSerializable()
class AccountFilter {
  @JsonKey(fromJson: toDouble)
  double latitude;
  @JsonKey(fromJson: toDouble)
  double longitude;
  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);
}

基本上,我将方法toDouble设置为@JsonKey注解中的fromJson参数,用于正确解析数据。

相关问题