json - 如何使用另一个类和JsonKey排除DART Model中的字段?

标签 json flutter dart model json-serialization

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

@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 Serializable包来处理JSON数据,因此如果我可以使用JsonKey(ignore:true)从扩展模型的单独类中排除不需要的字段,那将是很棒的。我不确定是否还有其他方法可以做到。有人可以在这种情况下帮助我吗?提前致谢!

最佳答案

我认为您在这里缺少其他步骤。您将无法使用dart模型作为HTTP请求的数据有效负载。您将需要以String格式映射其键,然后对映射进行jsonEncode。

您可以执行类似的操作以从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;
}

有关更多详细信息:Refer to this link

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

关于json - 如何使用另一个类和JsonKey排除DART Model中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60030671/

相关文章:

firebase - 用于 flutter 的 firebase_admob 0.6.1 的 App ID 问题

android - 如何在 flutter 中为 facebook 生成 key 哈希

flutter - 围绕其中心旋转绘制的文本

flutter - LocalStorage 流未完成?

flutter - 如何在flutter中设置State数据?

javascript - ng-选择 AngularJS

java - GSON内部工作

dart - 如何让 AppBar 保持在屏幕顶部

javascript - 将字符串值解析为对象

android - 确保 URL 是否提供 JSON