json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

How to use fromJson and toJson to split it into 2 fields

Open flikkr opened this issue 3 months ago • 0 comments

I have this Destination class where I store a LatLong object which also uses json serializable, and has a latitude and longitude field. I want the output of LatLong to not be nested in a coordinates field. Similarly, fromJson should parse the lat and long and create a LatLong object.

part 'destination.g.dart';

@JsonSerializable()
class Destination {
  final int id;
  final LatLong coordinates;

  Destination({
    required this.id,
    required this.coordinates,
  });

  factory Destination.fromJson(Map<String, dynamic> json) => _$DestinationFromJson(json);
}

The output should be:

{
  "id": 1,
  "latitude": 1,
  "longitude": 1
}

But my current approach outputs like this:

{
  "id": 1,
  "coordinates": {
    "latitude": 1,
    "longitude": 1
  }
}

I want to avoid creating a latitude and longitude field in my Destination class. Is there a way to achieve this?

flikkr avatar Apr 03 '24 02:04 flikkr