Search code examples
jsonflutterdartmodeljson-serialization

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


I have a model as shown below.

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

In another part of the application, I need to send the Vehicle object to and API end point, like this.

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

This is where I need to remove/exclude the additional fields such as seats and tires from the Car object.

int responseCode = await sendData(vehicle: car);

I'm using Json Serializable package for handling JSON data and so it would be great if I could use JsonKey(ignore: true) to exclude the unwanted fields from a separate class which is extending the model. I'm not sure if there is any other way to do it. Can someone please help me with this situation here? Thanks in advance!


Solution

  • I think you are missing an additional step here. You will not be able to use a dart model as data payload for HTTP requests. You will need to map it's keys in String format and then jsonEncode the map.

    You could do something like this to exclude the unwanted fields from a dart 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;
    }
    

    For more details: Refer to this link

    I'm not sure if it is the best approach, but let me know how that goes.