Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
flikkr opened this issue Apr 3, 2024 · 0 comments
Open

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

flikkr opened this issue Apr 3, 2024 · 0 comments

Comments

@flikkr
Copy link

flikkr commented Apr 3, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant