google / google/json_serializable.dart

Dynamic parsing with the help of an additional type parameter

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

Description

I successfully achieved dynamic parsing with the help of another parameter in the same JSON. Like this:
```dart
@JsonSerializable()
class MySpecialModel {
...
final DataType type;
@JsonKey(fromJson: _dataFromJson, readValue: _dataReadValue,)
final dynamic data;
...

static Data _dataReadValue(Map json, String key) {
DataType type = DataType.values.byName(json['type']);
return Data(type, json[key]);
}

static String _dataFromJson(Data value) {
switch (value.type) {
case DataType.first:
return DataFirst.fromJson(value.data);
case DataType.second:
return DataSecond.fromJson(value.data);
case DataType.third:
return DataThird.fromJson(value.data);
}
}

@JsonSerializable()
class Data {
final DataType type;
final dynamic data;

Data(this.type, this.data);
}

```
This is great! Thank you for your hard work.

The issue is that I have a list of these objects. Like:
```dart
@JsonSerializable()
class MyParentSpecialModel {
final List mySpecialModels;
```

It would be more suitable for the backend to return the type of data in the parent model. Like:
```dart
@JsonSerializable()
class MyParentSpecialModel {
final DataType type;
final List mySpecialModels;
```

So the objects of the list would not have the repeated type over and over again.

How can I 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.