google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.54k stars 393 forks source link

serialize parent attribute in child class #1355

Open giacomomasseron opened 10 months ago

giacomomasseron commented 10 months ago

Hi,
I have this parent class:

@JsonSerializable()
class Parent extends Grandpa {
  final Item item;

  const Parent({
    required id,
  }) : super(
          id: id,
        );

  factory Parent.fromJson(Map<String, dynamic> json) =>
      _$ParentFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$ParentToJson(this);
}

And this child class:

@JsonSerializable()
class Child extends Parent {
  final List<int> quantities;

  const Child({
    required id,
    required item,
  }) : super(
          id: id,
          item: item,
        );

  factory Child.fromJson(Map<String, dynamic> json) =>
      _$ChildFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$ChildToJson(this);
}

The script generates this code:

// GENERATED CODE - DO NOT MODIFY BY HAND

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Child _$ChildFromJson(Map<String, dynamic> json) =>
    Child(
      id: json['id'],
      item: json['item'], // <---- HERE I GET THE ERROR
    );

Map<String, dynamic> _$ChildToJson(Child instance) =>
    <String, dynamic>{
      'id': instance.id,
      'item': instance.item,
    };

But I have an error cause json['item'] is not a String, is a Map that should be converted with Item.fromJson(json['item'] as Map<String, dynamic>)

patterueldev commented 9 months ago

This still occurs right now. The error that causes this is when you call toJson(), the "json" map that's being created has the Instance of the child instead of the Json map.

This should be addressed. We could have a workaround by adding .toJson() to the child, but that's inconvenient.