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

How to exclude fields in a DART Model using another class and JsonKey?

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

@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

这是我需要 remove/exclude 附加字段的地方,例如 Car 对象的座位和轮胎。

int responseCode = await sendData(vehicle: car);

我正在使用 Json 可序列化包来处理 JSON 数据,所以如果我可以使用 JsonKey(ignore: true) 来排除不需要的字段,那就太好了来自扩展模型的单独 class。我不确定是否还有其他方法可以做到。有人可以帮我解决这种情况吗?提前致谢!

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

您可以像这样从飞镖中排除不需要的字段 class。

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;
}

更多详情:Refer to this link

我不确定这是否是最好的方法,但请告诉我情况如何。