google / google/json_serializable.dart

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

Open
#1,412 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

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.

```dart
part 'destination.g.dart';

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

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

factory Destination.fromJson(Map json) => _$DestinationFromJson(json);
}
```

The output should be:
```json
{
"id": 1,
"latitude": 1,
"longitude": 1
}
```

But my current approach outputs like this:
```json
{
"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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.