我正在努力json序列化。
未处理异常:类型'String'不是类型'num '的子类型?我试图使用自定义JSON转换器,但它不起作用。当我尝试从API获取数据时,当它开始反序列化JSON时,就会发生这种情况。
有谁知道怎么回事吗?
当它试图解析lat和lng值时发生错误。当它解析这两个值时,它抛出一个异常,类型String list不是类型num的子类型。在类型转换中。它发生在car_model.g中。当它运行这两行时:
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,
};
标题>标题>标题>这是因为有时你会得到
"lat": "50.754",
"lng": "12.2145"
表示它是字符串。所以你可以跟随下面的
final dynamic lat;
final dynamic lng;
然后再次使用模型生成器工具生成模型。
对于自动创建模型,您可以使用https://ashamp.github.io/jsonToDartModel/,它也提供了null安全功能。
[
{
"_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
}
)
Array在末尾有一个额外的逗号。我希望这就是问题所在
您可以使用https://app.quicktype.io/网站进行从json模型到dart模型的转换。
TOFAŞK & lt; 3
您可以尝试另一个代码生成器并完全控制您得到的内容。
这是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