【问题标题】:How to exclude fields in a DART Model using another class and JsonKey?如何使用另一个类和 JsonKey 排除 DART 模型中的字段?
【发布时间】:2020-02-02 21:18:25
【问题描述】:

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

@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) 从扩展模型的单独类中排除不需要的字段,那就太好了。我不确定是否有其他方法可以做到这一点。有人可以帮我解决这种情况吗?提前致谢!

【问题讨论】:

    标签: json flutter dart model json-serialization


    【解决方案1】:

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

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

    【讨论】:

    • 这项工作很有魅力!感谢您指出我缺少的部分,不胜感激!
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2012-05-20
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多