flutter 未行程的例外状况:类型“String”不是类型“num?'在类型转换中

kpbwa7wx  于 2023-10-22  发布在  Flutter
关注(0)|答案(3)|浏览(134)

我正在与JSON序列化作斗争。
我犯了一个错误:“未处理的异常:类型“String”不是类型“num?' in type cast'。
我尝试使用自定义JSON转换器,但它不工作。当我尝试从API获取数据时,它会发生,当它开始执行JSON时。
有谁知道是怎么回事吗?
当它试图解析纬度和纬度值时会发生错误。当它解析这两个值时,它抛出一个异常,即String类型不是num类型的子类型。在类型转换中。在car_model.g.dart文件中,当它运行这两行代码时,会发生这种情况:

lat: (json['lat'] as num?)?.toDouble(),
lng: (json['lng'] as num?)?.toDouble(),
[
    {
        "_id": "5e5e40c4c0ea272d00000956",
        "brand": "Tofas",
        "model": "Sahin",
        "color": "#0fc0fc",
        "registration": "WA12345",
        "year": "2005-01-01T00:00:00.000Z",
        "ownerId": "5e5e3d7fc0ea272d00000824",
        "lat": 50.754,
        "lng": 12.2145
    },
]

实体

import 'package:equatable/equatable.dart';

abstract class Car extends Equatable {
  final String? id;
  final String? brand;
  final String? model;
  final String? color;
  final String? registration;
  final String? year;
  final String? ownerId;
  final double? lat;
  final double? lng;

  const Car({
    this.id,
    this.brand,
    this.model,
    this.color,
    this.registration,
    this.year,
    this.ownerId,
    this.lat,
    this.lng,
  });

  @override
  List<Object?> get props => [
        id,
        brand,
        model,
        color,
        registration,
        year,
        ownerId,
        lat,
        lng,
      ];
}

型号

part 'car_model.g.dart';

class CarModelList {
  final List<CarModel> carModelList;

  CarModelList({
    required this.carModelList,
  });

  factory CarModelList.fromJson(List<dynamic> parsedJson) {
    List<CarModel> carModelList = <CarModel>[];
    carModelList = parsedJson.map((i) => CarModel.fromJson(i)).toList();

    return CarModelList(carModelList: carModelList);
  }
}

@JsonSerializable()
class CarModel extends Car {
  const CarModel({
    super.id,
    super.brand,
    super.model,
    super.color,
    super.registration,
    super.year,
    super.ownerId,
    super.lat,
    super.lng,
  });

  @JsonKey(name: '_id')
  @override
  String? get id;

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

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

模型生成

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'car_model.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

CarModel _$CarModelFromJson(Map<String, dynamic> json) => CarModel(
      id: json['_id'] as String?,
      brand: json['brand'] as String?,
      model: json['model'] as String?,
      color: json['color'] as String?,
      registration: json['registration'] as String?,
      year: json['year'] as String?,
      ownerId: json['ownerId'] as String?,
      lat: (json['lat'] as num?)?.toDouble(),
      lng: (json['lng'] as num?)?.toDouble(),
    );

Map<String, dynamic> _$CarModelToJson(CarModel instance) => <String, dynamic>{
      'brand': instance.brand,
      'model': instance.model,
      'color': instance.color,
      'registration': instance.registration,
      'year': instance.year,
      'ownerId': instance.ownerId,
      'lat': instance.lat,
      'lng': instance.lng,
      '_id': instance.id,
    };
rbpvctlc

rbpvctlc1#

这是因为有时你会得到

"lat": "50.754",
    "lng": "12.2145"

这意味着它是字符串。所以你可以按照下面的东西

final dynamic lat;
  final dynamic lng;

然后再次使用模型生成器工具生成模型。
对于模型的自动创建,你可以使用https://ashamp.github.io/jsonToDartModel/,它也提供了空安全的功能。

kninwzqo

kninwzqo2#

[
{
    "_id": "5e5e40c4c0ea272d00000956",
    "brand": "Tofas",
    "model": "Sahin",
    "color": "#0fc0fc",
    "registration": "WA12345",
    "year": "2005-01-01T00:00:00.000Z",
    "ownerId": "5e5e3d7fc0ea272d00000824",
    "lat": 50.754,
    "lng": 12.2145
}

]
数组末尾多了一个逗号。我希望这就是问题所在
您可以使用https://app.quicktype.io/网站从json模型到dart模型转换。

TOFANOK <3

lsmepo6l

lsmepo6l3#

你可以尝试另一个代码生成器,并完全控制你得到什么。
这就是CarModel类的描述。

CarModel:
  extends: Car
  fields:
    id: String?
    brand: String?
    model: String?
    color: String?
    registration: String?
    year: String?
    ownerId: String?
    lat:
      type: double
      deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
      serialize: "(x) { return  '$x'; }"
    lng:
      type: double
      deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
      serialize: "(x) { return  '$x'; }"

生成器.

import 'dart:io';

import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';

void main() {
  String generateName(String name) {
    return '_${name}Serializer';
  }

  final classes = loadYaml(_classes) as Map;
  final g = JsonSerializerGenerator();
  final classesCode = g.generateClasses(classes);

  final values = {
    'classes': classesCode,
  };

  var source = g.render(_template, values);
  source = g.format(source);
  File('bin/stackoverflow.dart').writeAsStringSync(source);
}

const _classes = r'''
CarModel:
  extends: Car
  fields:
    id: String?
    brand: String?
    model: String?
    color: String?
    registration: String?
    year: String?
    ownerId: String?
    lat:
      type: double
      deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
      serialize: "(x) { return  '$x'; }"
    lng:
      type: double
      deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
      serialize: "(x) { return  '$x'; }"
''';

const _template = r'''
import 'dart:convert';

void main(List<String> args) {
  final carModel = CarModel(
      id: null,
      brand: null,
      model: null,
      color: null,
      registration: null,
      year: null,
      ownerId: null,
      lat: 12.2145,
      lng: 50.754);

  final list = CarModel.toJsonList([carModel]);
  final List<CarModel> carModels = CarModel.fromJsonList(list);
  print('lat type: ${list[0]['lat'].runtimeType}');
  print(jsonEncode(list));
  print(carModels.first.lat);
  print(carModels.first.lng);
  print(carModels.first.lng.runtimeType);
}

{{classes}}
''';

生成的源代码:

import 'dart:convert';

void main(List<String> args) {
  final carModel = CarModel(
      id: null,
      brand: null,
      model: null,
      color: null,
      registration: null,
      year: null,
      ownerId: null,
      lat: 12.2145,
      lng: 50.754);

  final list = CarModel.toJsonList([carModel]);
  final List<CarModel> carModels = CarModel.fromJsonList(list);
  print('lat type: ${list[0]['lat'].runtimeType}');
  print(jsonEncode(list));
  print(carModels.first.lat);
  print(carModels.first.lng);
  print(carModels.first.lng.runtimeType);
}

class CarModel extends Car {
  CarModel(
      {required this.id,
      required this.brand,
      required this.model,
      required this.color,
      required this.registration,
      required this.year,
      required this.ownerId,
      required this.lat,
      required this.lng});

  factory CarModel.fromJson(Map json) {
    return CarModel(
      id: json['id'] as String?,
      brand: json['brand'] as String?,
      model: json['model'] as String?,
      color: json['color'] as String?,
      registration: json['registration'] as String?,
      year: json['year'] as String?,
      ownerId: json['ownerId'] as String?,
      lat: (x) {
        return x == null ? 0.0 : double.parse('$x');
      }(json['lat']),
      lng: (x) {
        return x == null ? 0.0 : double.parse('$x');
      }(json['lng']),
    );
  }

  final String? id;

  final String? brand;

  final String? model;

  final String? color;

  final String? registration;

  final String? year;

  final String? ownerId;

  final double lat;

  final double lng;

  static List<CarModel> fromJsonList(List json) {
    return json.map((e) => CarModel.fromJson(e as Map)).toList();
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'brand': brand,
      'model': model,
      'color': color,
      'registration': registration,
      'year': year,
      'ownerId': ownerId,
      'lat': (x) {
        return '$x';
      }(lat),
      'lng': (x) {
        return '$x';
      }(lng),
    };
  }

  static List<Map<String, dynamic>> toJsonList(List<CarModel> list) {
    return list.map((e) => e.toJson()).toList();
  }
}

输出量:

lat type: String
[{"id":null,"brand":null,"model":null,"color":null,"registration":null,"year":null,"ownerId":null,"lat":"12.2145","lng":"50.754"}]
12.2145
50.754
double

相关问题