我正在嘗試使用這個包 - https://pub.dev/packages/json_serializable來幫助我決議來自 api 的資料。但是我面臨以下錯誤,我不知道如何解決它。
我收到這個錯誤A value of type 'Location' can't be returned from the method 'toJson' because it has a return type of 'Map<String, dynamic>
@JsonSerializable()
class Location {
const Location({
required this.title,
required this.locationType,
required this.latLng,
required this.woeid,
});
final String title;
final LocationType locationType;
final LatLng latLng;
final int woeid;
factory Location.fromJson(Map<String,dynamic> json) => _$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationFromJson(this);
}
每當我將最后一部分更改為Location toJson() => _$LocationFromJson(this);然后我得到錯誤The argument type 'Location' can't be assigned to the parameter type 'Map<String, dynamic>
uj5u.com熱心網友回復:
您需要將復雜的資料型別轉換為簡單的資料型別,如String、int、double等,以便在json中決議。這是有關如何實作緯度和經度的示例。
假設我有一個學校資料,我想為其存盤名稱和位置。我會為名稱創建一個簡單的字串,但為位置創建一個單獨的類。這是怎么回事:
class SchoolDataModel {
final String name;
final SchoolLocation schoolLocation;
SchoolDataModel({
required this.name,
required this.schoolLocation,
});
factory SchoolDataModel.fromJson(Map<String, dynamic> parsedJson) =>
SchoolDataModel(
name: parsedJson['name'] as String,
schoolLocation: SchoolLocation.fromJson(
parsedJson['location'] as Map<String, dynamic>),
);
}
如您所見,SchoolLocation.fromJson 用于使用自己的建構式決議位置資料。如下所示:
class SchoolLocation {
final String latitude;
final String longitude;
SchoolLocation({
required this.latitude,
required this.longitude,
});
factory SchoolLocation.fromJson(Map<String, dynamic> parsedJson) =>
SchoolLocation(
latitude: parsedJson['latitude'] as String,
longitude: parsedJson['longitude'] as String,
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471866.html
上一篇:顫動中具有相互類名的Web報廢表
