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);
}
Try this approach, it is more cleaner, and you don't even need the
JsonSerializable.1- ProductEntity class:
2- CategoryEntity class: