如何使用另一个类和 JsonKey 排除 DART 模型中的字段?



我有一个如下所示的模型。

@JsonSerializable()
class Vehicle{
final String name;
final String make;
final String model;
final int year;
final int tires;
final int seats;
Vehicle({
this.name,
this.make,
this.model,
this.year,
this.tires,
this.seats
});
factory Vehicle.fromJson(Map<String, dynamic> json, int vehicleOwnerId) {
var response = _$VehicleFromJson(json);
response.vehicleOwnerId = vehicleOwnerId;
return response;
}
Map<String, dynamic> toJson() => _$VehicleToJson(this);
}

在应用程序的另一部分,我需要将 Vehicle 对象发送到 API 端点,如下所示。

Future<int> sendData({Vehicle vehicle}){
final Response response = await put(
Uri.https(apiEndpoint, {"auth": authKey}),
headers: headers,
body: vehicle);
return response.statusCode;
}
Vehicle car;
// remove/exclude unwanted fields

这是我需要从 Car 对象中删除/排除座椅和轮胎等附加字段的地方。

int responseCode = await sendData(vehicle: car);

我正在使用 Json 可序列化包来处理 JSON 数据,因此如果我可以使用 JsonKey(忽略:true(从扩展模型的单独类中排除不需要的字段,那就太好了。我不确定是否有其他方法可以做到这一点。有人可以在这里帮助我解决这种情况吗?提前感谢!

我认为您在这里缺少一个额外的步骤。您将无法使用 dart 模型作为 HTTP 请求的数据负载。您需要以字符串格式映射其键,然后对映射进行 jsonEncoding 。

您可以执行类似操作以从 dart 类中排除不需要的字段。

Vehicle car;
int responseCode = await sendData(vehicle: car);
Future<int> sendData({Vehicle vehicle}){
Map<String dynamic> mappedVehicle = vehicle.toJson();
vehicle.remove("tires");
vehicle.remove("seats");
// This will remove the fields 
var finalVehicle = jsonEncode(mappedVehicle);
final Response response = await put(
Uri.https(apiEndpoint, {"auth": authKey}),
headers: headers,
body: finalVehicle);
return response.statusCode;
}

有关更多详细信息:请参阅此链接

我不确定这是否是最好的方法,但请告诉我这是怎么回事。

最新更新