How to generate a JsonSerializable with extended class

33 views Asked by At

I'm creating a product app in clean architucture, I want to generate json but I cant to do it with JsonSerializable but I cant do it I always get error

Could not generate `fromJson` code for `categories` because of type `CategoryEntity`.
package:mermate/features/products/domain/entities/product_entity.dart:6:30
  ╷
6 │   final List<CategoryEntity> categories;
  │                              ^^^^^^^^^^

I tried that,

domain/product_entity.dart

class ProductEntity extends Equatable {
  final int id;
  final List<CategoryEntity> categories;

  const ProductEntity({required this.id, required this.categories});

  @override
  List<Object> get props => [id, categories];
}

class CategoryEntity extends Equatable {
  final int id;

  const CategoryEntity({required this.id});

  @override
  List<Object> get props => [id];
}

data/product_model.dart

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:mermate/features/products/domain/entities/product_entity.dart';
part 'product_model.g.dart';

@JsonSerializable(explicitToJson: true)
class ProductModel extends ProductEntity {
  const ProductModel({required super.id, required super.categories});
  factory ProductModel.fromJson(Map<String, dynamic> json) =>
      _$ProductModelFromJson(json);
  Map<String, dynamic> toJson() => _$ProductModelToJson(this);
}

@JsonSerializable()
class CategoryModel extends CategoryEntity {
  const CategoryModel({required super.id});
  factory CategoryModel.fromJson(Map<String, dynamic> json) =>
      _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);
}
1

There are 1 answers

2
Osama Remlawi On

Try this approach, it is more cleaner, and you don't even need the JsonSerializable.

1- ProductEntity class:

class ProductEntity extends Equatable {
  final int id;
  final List<CategoryEntity> categories;

  const ProductEntity({
    required this.id,
    required this.categories
  });

  @override
  List<Object> get props => [id, categories];

  static ProductEntity fromJson(
    Map<String, dynamic> json,
  ) {
    return ProductEntity(
      id: json['id'],
      categories: CategoryEntity.fromJsonList(json['categories']),
    );
  }
}

2- CategoryEntity class:

class CategoryEntity extends Equatable {
  final int id;

  const CategoryEntity({
    required this.id
  });

  @override
  List<Object> get props => [id];

  static CategoryEntity fromJson(
    Map<String, dynamic> json,
  ) {
    return CategoryEntity(
      id: json['id'],
    );
  }

  static List<CategoryEntity> fromJsonList(
    List<dynamic> jsonList,
  ) {
    if (jsonList == null) {
      return null;
    }
    return jsonList
        .map<CategoryEntity>(
          (
            dynamic jsonObject,
          ) =>
              CategoryEntity.fromJson(
            jsonObject,
          ),
        )
        .toList();
  }
}