You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Clean架构下如何为继承类生成JsonSerializable序列化代码

解决JsonSerializable生成嵌套类型序列化代码失败的问题

错误信息

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;
│ ^^^^^^^^^^

问题原因

你在Clean Architecture架构下让Data层的ProductModel直接继承了Domain层的ProductEntity,但Domain层的CategoryEntity属于纯业务实体,没有添加@JsonSerializable注解或序列化逻辑。JsonSerializable仅能识别带有自身注解的类,无法处理无序列化配置的实体类,因此生成代码时无法解析List<CategoryEntity>类型。同时这种继承方式也违背了Clean Architecture分层隔离的设计原则。

解决方案

调整Model层结构,让Model类独立负责序列化逻辑,通过转换方法将Model转为Domain层的Entity,而非直接继承。

修改后的代码示例

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:json_annotation/json_annotation.dart';
import 'package:mermate/features/products/domain/entities/product_entity.dart';
part 'product_model.g.dart';

@JsonSerializable(explicitToJson: true)
class ProductModel {
  final int id;
  final List<CategoryModel> categories;

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

  factory ProductModel.fromJson(Map<String, dynamic> json) => _$ProductModelFromJson(json);
  Map<String, dynamic> toJson() => _$ProductModelToJson(this);

  // 将Model转换为Domain层Entity
  ProductEntity toEntity() {
    return ProductEntity(
      id: id,
      categories: categories.map((category) => category.toEntity()).toList(),
    );
  }
}

@JsonSerializable()
class CategoryModel {
  final int id;

  const CategoryModel({required this.id});

  factory CategoryModel.fromJson(Map<String, dynamic> json) => _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);

  // 将Model转换为Domain层Entity
  CategoryEntity toEntity() {
    return CategoryEntity(id: id);
  }
}

说明

  1. Model独立序列化:ProductModel和CategoryModel不再继承Entity,自身持有对应字段并添加@JsonSerializable注解,让JsonSerializable能正常生成序列化代码。
  2. 分层转换:通过toEntity()方法将Data层的Model转换为Domain层的纯实体,既满足Clean Architecture的分层隔离要求,也解决了序列化类型不兼容的问题。
  3. explicitToJson参数:ProductModel上的explicitToJson: true确保嵌套的CategoryModel能被正确序列化。

内容的提问来源于stack exchange,提问作者Rio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:55:15