google / google/json_serializable.dart
toJson and fromJson work differently with nested objects
- Dominant language
- Dart
- Stars
- 1.6k
- Forks
- 461
- Avg merge
- 45m
- Merged PRs (30d)
- 1
Description
The two methods are working in different ways
for example using t`hese classes:`
```
@JsonSerializable()
class Parent {
String name;
String surname;
Child child1;
Child child2;
factory Parent.fromJson(Map json) => _$ParentFromJson(json);
Parent({required this.name, required this.surname, required this.child1, required this.child2});
Map toJson() => _$ParentToJson(this);
}
@JsonSerializable()
class Child {
String name;
String surname;
factory Child.fromJson(Map json) => _$ChildFromJson(json);
Child({required this.name, required this.surname});
Map toJson() => _$ChildToJson(this);
}
```
the fromJson methods are correctly:
```
Parent _$ParentFromJson(Map json) => Parent(
name: json['name'] as String,
surname: json['surname'] as String,
child1: Child.fromJson(json['child1'] as Map),
child2: Child.fromJson(json['child2'] as Map),
);
Child _$ChildFromJson(Map json) =>
Child(name: json['name'] as String, surname: json['surname'] as String);
```
instead the toJson methods are the following
```
Map _$ParentToJson(Parent instance) => {
'name': instance.name,
'surname': instance.surname,
'child1': instance.child1,
'child2': instance.child2,
};
Map _$ChildToJson(Child instance) => {
'name': instance.name,
'surname': instance.surname,
};
```
with nested objects the toJson method doesn't convert the object in json.
As workaround at the moment is required to define a custom method to parse the nested object and pass it in the annotation
```
@JsonSerializable()
class Parent {
String name;
String surname;
@JsonKey(toJson: childToJson)
Child child1;
@JsonKey(toJson: childToJson)
Child child2;
factory Parent.fromJson(Map json) => _$ParentFromJson(json);
Parent({required this.name, required this.surname, required this.child1, required this.child2});
Map toJson() => _$ParentToJson(this);
}
```
```
Map _$ParentToJson(Parent instance) => {
'name': instance.name,
'surname': instance.surname,
'child1': childToJson(instance.child1),
'child2': childToJson(instance.child2),
};
```
Contributor guide
Assessment
This issue has not been assessed yet.